1 / 98

Swift Programming Language Guide - Part 1

A comprehensive guide for learning the Swift programming language, covering topics such as closures, arrays, dictionaries, enums, and more.

sfox
Télécharger la présentation

Swift Programming Language Guide - Part 1

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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

  2. 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

  3. 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.

  4. HelloWorld! Asusualwewillstartwithprinting"HelloWorld"message.Wewill usesomethingcalledplaygroundtoexploreSwiftlanguage.It'san amazingtooltowriteanddebugcodewithoutcompileorrun. CreateoropenanXcodeproject and create newplayground:

  5. HelloWorld! Use"NSLog"or"println"toprintmessagetoconsole.Asyouseein the right side you can see in real time the values of variables or consolemessage.

  6. 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:

  7. Variables &Constants.

  8. Variables &Constants. InObjective-Cweusedtousemutability,forexample: NSArrayandNSMutableArrayorNSStringandNSMutableString InSwift,whenyouusevar,allobjectswillbemutable BUT whenyou uselet,allobjectswillbeimmutable:

  9. PrintingOutput • Weintroducedthenewwaytoprintoutputusingprintln().Its verysimilartoNSLog()butNSLogisslower,addstimestampto output message and appear in device log. Println() appear in debugger logonly. • InSwiftyoucaninsertvaluesofvariablesinsideStringusing"\()"a backslash with parentheses, checkexample:

  10. TypeConversion Swiftisunlikeotherlanguages,itwillnotimplicitlyconverttypesof resultofstatements.LetscheckexampleinObj-C: InSwiftyoucan'tdothis.Youhavetodecidethetypeofresultby explicitlyconvertingittoDoubleorInteger.Checknextexample:

  11. TypeConversion Hereweshouldconvertanyoneofthemsothetwovariablesbeinsame type. Swiftguaranteessafetyinyourcodeandmakesyoudecidethetypeof yourresult.

  12. InSwift,youdon'thavetoaddparenthesesaroundthecondition. Butyoushouldusethemincomplexconditions. If • Curlybraces{}arerequiredaroundblockofcodeafterIforelse. Thisalsoprovidesafetytoyourcode.

  13. If • ConditionsmustbeBoolean,trueorfalse.Thus,thenextcode willnotworkasitwasworkinginObjective-C: AsyouseeinSwift,youcannotcheckinvariabledirectlylike Objective-C.

  14. IfWithOptionals • YoucansetthevariablevalueasOptionaltoindicatethatitmay contain a value ornil. • Writequestionmark"?"afterthetypeofvariabletomarkitas Optional. • Thinkofitlikethe"weak"property,itmaypointtoanobjectornil • UseletwithIftochecktheOptionalvalue.Iftheoptionalvalueis nil,theconditionalwillbefalse.OtherWise,theitwillbetrueand thevaluewillbeassignedtotheconstantoflet • Checkexample:

  15. IfWithOptionals

  16. 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:

  17. Switch

  18. SwitchCont. • As we said, there is no fallthrough in switch statements and thereforebreakisnotrequired.Socodelikethiswillnotworkin Swift: • Asyousee,eachcasemustcontainatleastoneexecutable statement. • Multiplematchesforsingle case canbeseparatedbycommasand noneedforfallthroughcases

  19. SwitchCont.

  20. Switch WithRanges. • InSwiftyoucanusetherangeofvaluesforcheckingincase statements.Rangesareidentifiedwith"..."inSwift:

  21. 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:

  22. Switch WithTuples. • Decomposing: • Useunderscore"_"toignoreparts:

  23. Switch WithTuples. • Youcanuseelementindextoaccesstuplevalues.Alsoyoucan nametheelementsandaccessthembyname: • Withdictionary:

  24. Switch WithTuples. Using tuples withfunctions:

  25. 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:

  26. Switch WithTuples.

  27. Switch With ValueBinding Youcanbindthevaluesofvariablesinswitch case statementsto temporaryconstantstobeusedinsidethecasebody:

  28. Switch With"Where" "Where"isusedwithcasestatementtoaddadditionalcondition. Check theseexamples:

  29. Switch With"Where" Anotherexampleinusing"Where":

  30. Loops • Likeotherlanguages,youcanuseforandfor-inloopswithout changes.ButinSwiftyoudon'thavetowritetheparentheses. • for-inloopscaniterateanycollectionofdata.AlsoItcanbeused withranges

  31. 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:

  32. Functions • Using names forlocal variables

  33. Functions • InSwift,paramsareconsideredasconstantsandyoucan'tchange them. • To change local variables, copy the values to other variables OR tellSwiftthatthisvalueisnotconstantbywriting'var'beforethe name:

  34. 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:

  35. Functions • Using default parametervalue: • Functionscantakevariablenumberofargumentsusing'...':

  36. Passing&ReturningFunctions • InSwift,functionsarefirstclassobjects.Thustheycanbepassed around • Everyfunctionhastypelikethis: • Youcanpass a functionasparameterorreturnitas a result. Checkexamples:

  37. Passing&ReturningFunctions

  38. 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.

  39. Closures • Example#1,usingmapwithanarray.mapreturnsanarraywith result ofeach item

  40. Closures • Example#2ofusingclosureascompletionhandlerwhensending apirequest

  41. Closures • Example #3, using the built-in "sorted" function to sort any collectionbasedon a closurethatwilldecidethecompareresult ofanytwoitems

  42. 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.

  43. Arrays • Creatingandinitializingarrayiseasy.Alsoyoucancreatearray withcertainsizeanddefaultvalueforitems: • Forappendingitems,use'append'methodor"+=":

  44. Arrays • Youcanretrieveandupdatearrayusingsubscriptsyntax.Youwill getruntimeerrorifyoutriedto access itemoutofbound.

  45. Arrays • You can easily iterate over an array using 'for-in' , 'for' or by 'enumerate'.'enumerate'givesyoutheitemanditsindexduring enumeration.

  46. Dictionaries • DictionaryinSwiftissimilartooneinObjective-CbutlikeArray, Dictionaryisstronglytyped,allkeysmustbeinsametypeandall valuesmustbeinsametype. • TypeofDictionaryisinferredbyinitialvaluesoryouhavetowrite thetypebetweensquarebrackets[KeyType,ValueType] • Like Arrays, Dictionaries by default are mutable dictionaries, exceptifyoudefineditasconstantusing'let'itwillbeimmutable. • Check examples:)

  47. Dictionaries

  48. Enum • Enumisverypopularconceptifyouhavespecificvaluesof something. • Enumiscreatedbythekeyword'enum'andlistingallpossible casesafterthekeyword'case'

  49. Enum • Enumcanbeusedeasilyinswitchcase butasweknowthatswitch inSwiftisexhaustive,youhavetolistallpossible cases.

  50. 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")

More Related