980 likes | 1.07k Views
A comprehensive guide for learning the Swift programming language, covering topics such as closures, arrays, dictionaries, enums, and more.
E N D
https://www.slideshare.net/HossamGhareeb/the-complete-guide-for-swift-programming-language-part-1-41912848?qid=70da6288-4ebd-4c31-b8c0-4bd975eb8070&v=&b=&from_search=2https://www.slideshare.net/HossamGhareeb/the-complete-guide-for-swift-programming-language-part-1-41912848?qid=70da6288-4ebd-4c31-b8c0-4bd975eb8070&v=&b=&from_search=2 TheCompleteGuideFor ProgrammingLanguage Part1 By:HossamGhareeb hossam.ghareb@gmail.com
Contents. • Closures(Blocks) • Arrays • Dictionaries • Enum • AboutSwift • Hello World! withplayground • Variables &Constants • PrintingOutput • TypeConversion • If • If withoptionals • Switch • Switch WithRanges. • Switch WithTuples. • Switch With ValueBinding • Switch With"Where" • Loops • Functions • Passing & ReturningFunctions
AboutSwift • Swiftisanewscriptingprogramminglanguagefor iOS andOS X apps. • Swiftiseasy,flexibleandfunny. • UnlikeObjective-C,SwiftisnotCCompatible.Objective-Cis a supersetofCbutSwiftisnot. • SwiftisreadablelikeObjective-Canddesignedtobefamiliarto Objective-Cdevelopers. • Youdon'thavetowritesemicolons,butyoumustwriteitifyou wanttowritemultiplestatementsinsingleline. • YoucanstartwritingappswithSwiftlanguagestartingfrom Xcode6. • Swiftdoesn'trequiremainfunctiontostartwith.
HelloWorld! Asusualwewillstartwithprinting"HelloWorld"message.Wewill usesomethingcalledplaygroundtoexploreSwiftlanguage.It'san amazingtooltowriteanddebugcodewithoutcompileorrun. CreateoropenanXcodeproject and create newplayground:
HelloWorld! Use"NSLog"or"println"toprintmessagetoconsole.Asyouseein the right side you can see in real time the values of variables or consolemessage.
Variables &Constants. InSwift,use'let'forconstansand'var'forvariables.Inconstantsyou can't change the value of a constant after being initialized and you mustsetavaluetoit. Althoughyouuse'var'or'let'forvariables,Swiftistypedlanguage. The type is written after ':' . You don't have to write the type of variableorconstantbecausethecompilerwillinferitusingitsinitial value. BUT if you didn't set an initial value or the initial value that you providedisnotenoughtodeterminethetype,youhavetoexplicitly typethevariableorconstants. Checkexamples:
Variables &Constants. InObjective-Cweusedtousemutability,forexample: NSArrayandNSMutableArrayorNSStringandNSMutableString InSwift,whenyouusevar,allobjectswillbemutable BUT whenyou uselet,allobjectswillbeimmutable:
PrintingOutput • Weintroducedthenewwaytoprintoutputusingprintln().Its verysimilartoNSLog()butNSLogisslower,addstimestampto output message and appear in device log. Println() appear in debugger logonly. • InSwiftyoucaninsertvaluesofvariablesinsideStringusing"\()"a backslash with parentheses, checkexample:
TypeConversion Swiftisunlikeotherlanguages,itwillnotimplicitlyconverttypesof resultofstatements.LetscheckexampleinObj-C: InSwiftyoucan'tdothis.Youhavetodecidethetypeofresultby explicitlyconvertingittoDoubleorInteger.Checknextexample:
TypeConversion Hereweshouldconvertanyoneofthemsothetwovariablesbeinsame type. Swiftguaranteessafetyinyourcodeandmakesyoudecidethetypeof yourresult.
InSwift,youdon'thavetoaddparenthesesaroundthecondition. Butyoushouldusethemincomplexconditions. If • Curlybraces{}arerequiredaroundblockofcodeafterIforelse. Thisalsoprovidesafetytoyourcode.
If • ConditionsmustbeBoolean,trueorfalse.Thus,thenextcode willnotworkasitwasworkinginObjective-C: AsyouseeinSwift,youcannotcheckinvariabledirectlylike Objective-C.
IfWithOptionals • YoucansetthevariablevalueasOptionaltoindicatethatitmay contain a value ornil. • Writequestionmark"?"afterthetypeofvariabletomarkitas Optional. • Thinkofitlikethe"weak"property,itmaypointtoanobjectornil • UseletwithIftochecktheOptionalvalue.Iftheoptionalvalueis nil,theconditionalwillbefalse.OtherWise,theitwillbetrueand thevaluewillbeassignedtotheconstantoflet • Checkexample:
Switch • SwitchworksinSwiftlikemanyotherlanguagesbutwithsomenew features and smalldifferences: • Itsupportsanykindofdata,notonlyIntegers.Itchecksfor equality. • Switchstatementmustbeexhaustive.Itmeansthatyouhaveto cover(add cases for)allpossiblevaluesforyourvariable.Ifyou can't provide case statement for each value, add a default statementtocatchothervalues. • When a case is matched in switch, the program exits from the switchcaseanddoesn'tcontinuecheckingnext cases. Thus,you don'thavetoexplicitlybreakouttheswitchattheendofeach case. • Checkexamples:
SwitchCont. • As we said, there is no fallthrough in switch statements and thereforebreakisnotrequired.Socodelikethiswillnotworkin Swift: • Asyousee,eachcasemustcontainatleastoneexecutable statement. • Multiplematchesforsingle case canbeseparatedbycommasand noneedforfallthroughcases
Switch WithRanges. • InSwiftyoucanusetherangeofvaluesforcheckingincase statements.Rangesareidentifiedwith"..."inSwift:
Switch WithTuples. Tuplesareusedtogroupmultiplevaluesin a singlecompoundvalue. Eachvaluecanbeinanytype.Valuescanbewithanynumberasyou like: Youcandecomposethevaluesoftupleswithmanywaysasyouwill see in examples. Most of time, tuples are used to return multiple values from function. Also can be use to enumerate dictionary contents as (key, value). Checkexamples:
Switch WithTuples. • Decomposing: • Useunderscore"_"toignoreparts:
Switch WithTuples. • Youcanuseelementindextoaccesstuplevalues.Alsoyoucan nametheelementsandaccessthembyname: • Withdictionary:
Switch WithTuples. Using tuples withfunctions:
Switch WithTuples. Now we will see tuples with switch. We will use it in checking that a pointislocatedinside a boxingrid.Alsowewanttocheckifthepoint locatedonx-axisory-axis.Hereisthegird:
Switch With ValueBinding Youcanbindthevaluesofvariablesinswitch case statementsto temporaryconstantstobeusedinsidethecasebody:
Switch With"Where" "Where"isusedwithcasestatementtoaddadditionalcondition. Check theseexamples:
Switch With"Where" Anotherexampleinusing"Where":
Loops • Likeotherlanguages,youcanuseforandfor-inloopswithout changes.ButinSwiftyoudon'thavetowritetheparentheses. • for-inloopscaniterateanycollectionofdata.AlsoItcanbeused withranges
Functions • Functionsarecreatedusingthekeyword'func'. • Parenthesesarerequiredforfunctionsthatdon'ttakeparams. • Inparametersyoutypethenameandtypeofvariablebetween':' • You can describe or name the local variables of function like Objective-CbywritingthenamebeforethelocalvariableORadd '#' if the local variable is already an appropriate name. Check examples:
Functions • Using names forlocal variables
Functions • InSwift,paramsareconsideredasconstantsandyoucan'tchange them. • To change local variables, copy the values to other variables OR tellSwiftthatthisvalueisnotconstantbywriting'var'beforethe name:
Functions • Toreturnvalues,youhavetowritethetypeofreturnedinfoafter '()'and"->".Usetuplestoreturnmultiplevaluesatonce. • InSwift,youcanusedefaultparametervalues. BUT beawarethat when you wanna use function with default-valued params, you must write the name of the argument when you wanna use it. Checkexamples:
Functions • Using default parametervalue: • Functionscantakevariablenumberofargumentsusing'...':
Passing&ReturningFunctions • InSwift,functionsarefirstclassobjects.Thustheycanbepassed around • Everyfunctionhastypelikethis: • Youcanpass a functionasparameterorreturnitas a result. Checkexamples:
Closures • ClosuresareverysimilartoblocksinCandObjective-C. • Closuresarefirstclasstypesoitcanbenested,returnedand passed as parameter. (Same as blocks inObjective-C) • Functions are special cases ofclosures. • Closuresareenclosedincurlybraces{},thenwritethefunction type (arguments) -> (return type), followed by in keyword that separatetheclosureheaderfromthebody.
Closures • Example#1,usingmapwithanarray.mapreturnsanarraywith result ofeach item
Closures • Example#2ofusingclosureascompletionhandlerwhensending apirequest
Closures • Example #3, using the built-in "sorted" function to sort any collectionbasedon a closurethatwilldecidethecompareresult ofanytwoitems
Arrays • ArraysinSwiftaretyped.Youhavetochoosethetypeofarray, array of Integers, array of Strings,....etc. That's different from Objective-Cwhereyoucancreatearraywithitemsofanytype. • Youcanwritethetypeofarraybetweensquarebrackets[]ORIf you initialized it with data, Swift will infer the type of array implicitly. • Arraysbydefaultaremutablearrays,exceptifyoudefineditas constantusing'let'itwillbeimmutable. • Lengthofarraycanbeknowby.countproperty,andyoucan checkifisitemptyornotby.isEmptyproperty.
Arrays • Creatingandinitializingarrayiseasy.Alsoyoucancreatearray withcertainsizeanddefaultvalueforitems: • Forappendingitems,use'append'methodor"+=":
Arrays • Youcanretrieveandupdatearrayusingsubscriptsyntax.Youwill getruntimeerrorifyoutriedto access itemoutofbound.
Arrays • You can easily iterate over an array using 'for-in' , 'for' or by 'enumerate'.'enumerate'givesyoutheitemanditsindexduring enumeration.
Dictionaries • DictionaryinSwiftissimilartooneinObjective-CbutlikeArray, Dictionaryisstronglytyped,allkeysmustbeinsametypeandall valuesmustbeinsametype. • TypeofDictionaryisinferredbyinitialvaluesoryouhavetowrite thetypebetweensquarebrackets[KeyType,ValueType] • Like Arrays, Dictionaries by default are mutable dictionaries, exceptifyoudefineditasconstantusing'let'itwillbeimmutable. • Check examples:)
Enum • Enumisverypopularconceptifyouhavespecificvaluesof something. • Enumiscreatedbythekeyword'enum'andlistingallpossible casesafterthekeyword'case'
Enum • Enumcanbeusedeasilyinswitchcase butasweknowthatswitch inSwiftisexhaustive,youhavetolistallpossible cases.
Enum WithAssociated Values • Enumvaluescanbeusedwithassociatedvalues.Letsexplainwith an example. Suppose you describe products in your project, each producthas a barcode.Barcodeshave2types(UPC,QRCode) • UPCcodecanberepresentedby4Integers(4,88581,01497,3), andQRcodecanberepresentedbyString("ABCFFDF")