cs5530 mobile/wireless systems - college of engineering...
TRANSCRIPT
Ref.CN5E,NT@UW,WUSTLCS5530
CS5530Mobile/WirelessSystems
Swift
YanyanZhuangDepartmentofComputerSciencehttp://www.cs.uccs.edu/~yzhuang
UC.ColoradoSprings
catannounce.txt_
Ref.CN5E,NT@UW,WUSTL2CS5530
• iMacsremoteVNCaccesso VNP:http://www.uccs.edu/itservices/services/network-and-internet/vpn.html
o VNCpassword:cs5530
o PleasesavedatatoZ
o PleasedonotuseiMacsinLibrary
o ITwillupgrade…
Swift
Ref.CN5E,NT@UW,WUSTL3CS5530
• Whatisit?o AnewprogramminglanguageforAppleproducts
} iOS(ipods,iphones,ipads,etc.),macOS,watchOS,tvOS,future…
} Currentlyatversion3¨ Toseeyourversion:xcrun swift-version
¨ AppleSwiftversion3.0.2(swiftlang-800.0.63clang-800.0.42.1)
} Opensource
o BasedonObjective-CandC.} Classes,instances,properties,methods,inheritance,etc.
Swift
Ref.CN5E,NT@UW,WUSTL4CS5530
o RequiresanAppleproductfordevelopment} Air,MacBook,MacBookPro,iMac,iTrashCan (MacPro)
o Requiresthe‘Xcode’developmentenvironment,Appleonly.
o Resourcesat:} https://developer.apple.com/
Xcode Playground
Ref.CN5E,NT@UW,WUSTL5CS5530
o Aninteractiveworkenvironmentthatallowsyouupdatevaluesreal-timeandseeresults.
o A‘project’optioninXcode.
o NewforiPadiOS10!!!
Xcode Playground
Ref.CN5E,NT@UW,WUSTL6CS5530
Swift
Ref.CN5E,NT@UW,WUSTL7CS5530
• Quickoverviewofthelanguageo Assignments
o ControlFlow
o FunctionsandClosures
o ObjectsandClasses
o EnumerationsandStructures
o Protocols
o ErrorHandling
Swift- Overview
Ref.CN5E,NT@UW,WUSTL8CS5530
• “Don’tneedtoimportaseparatelibraryforfunctionalitylikeinput/outputorstringhandling.
• Codewrittenatglobalscopeisusedastheentrypointfortheprogram,soyoudon’tneedmain().
• Don’tneedtowritesemicolonsattheendofeverystatement.”• ExcerptFrom:AppleInc.“TheSwiftProgrammingLanguage(Swift3.0.1).”iBooks.
https://itun.es/ca/jEUH0.l
Swift- Assignments
Ref.CN5E,NT@UW,WUSTL9CS5530
o Typescanbe‘inferred’
o Canbeexplicit
o NOimplicittypeconversions} Valuesinstringsbyusinga“\”
let apples = 3
let applySummary = “I have \(apples) apples.”
Keyword Description
let Usedforconstants.Doesnotneedtobeknownatcompiletimebutmustbeassignedavalueexactly once.
var Usedforvariables.
Swift- Assignments
Ref.CN5E,NT@UW,WUSTL10CS5530
o Typescanbe‘inferred’o Canbeexplicito NOimplicittypeconversions
} Valuesinstringsbyusinga“\”let apples = 3
let applySummary = “I have \(apples) apples.”
} Valuesareneverimplicitlyconvertedtoanothertype.Ifneedtoconvertavaluetoadifferenttype,explicitlymakeaninstanceofthedesiredtype.
“TheSwiftProgrammingLanguage(Swift3.0.1).”
Keyword Description
let Usedforconstants.Doesnotneedtobeknownatcompiletimebutmustbeassignedavalueexactly once.
var Usedforvariables.
Swift- Assignments
Ref.CN5E,NT@UW,WUSTL11CS5530
• Assignmentso Dictionariesandarraysuse[]
var shoppingList = [“hp”, “apple”, “microsoft”]
shoppingList[1] = “Lenovo”
var occupations = ["Malcolm": "Captain", "Kaylee": "Mechanic"]
occupations["Jayne"] = "Public Relations”
o Emptyarraysordictionarieslet emptyArray = [String]()
Let emptyDictionary = [String: Float]()
Iftypeinformationcanbeinferred,canwriteanemptyarrayas[]andanemptydictionaryas[:]
• DataTypeso Typicaldatatypesavailable.
} String,Float,Double,Bool,Int/Uint,Character,Optional
Swift– ControlFlow
Ref.CN5E,NT@UW,WUSTL12CS5530
• For/ifexampleo Ifconditionmustbeexplicit
o ifscore{..}isanerror
Keyword Description
if, switch Usedforconditionals.Parenthesisaroundvariableareoptional.Bracesaroundconditional bodyarerequired.
for-in, for, while, repeat-while
Usedfor loops.Parenthesisaroundvariableareoptional.Bracesaroundloopbodyarerequired.
Swift– ControlFlow
Ref.CN5E,NT@UW,WUSTL13CS5530
• Switch
Swift– ControlFlow
Ref.CN5E,NT@UW,WUSTL14CS5530
• Switcho letcanbeusedinapatterntoassignvalue
o Noneedtobreak} Onlyonematch
Swift– ControlFlow
Ref.CN5E,NT@UW,WUSTL15CS5530
• for-ino Iterateoveritemsinadictionarybyprovidingapairofnamestouseforeachkey-valuepair.
o Dictionariesareunordered!
Swift– ControlFlow
Ref.CN5E,NT@UW,WUSTL16CS5530
o While&repeat-while} SameasCorJava’swhile&do-while.
} repeat{…}whilesome-condition
o Forloopsstillthesame} Thoughyoucanuse..< or ... tomakeranges.
¨ 0..<7 non-inclusiveupperbound.
¨ for i in 0..<7 { … }
¨ 0...7 inclusiveupperbound
¨ for i in 0...7 { … }
Swift– Functions&Closures
Ref.CN5E,NT@UW,WUSTL17CS5530
• Usefunc todeclareafunctiono à toindicatereturntype
o Useatupletomakeacompoundvalue:returnmultiplevaluesfromafunction
} Elementsofatuplecanbereferredtobynameorbynumber
} Definedas……à (min: Int, max: Int, sum: Int)
} Accessasresults.sum, or results.2
Swift– Functions&Closures
Ref.CN5E,NT@UW,WUSTL18CS5530
o Cantakevariablearguments,collectsintoanarrayforyou.
o Canbenested.
Swift– Functions&Closures
Ref.CN5E,NT@UW,WUSTL19CS5530
o Functionsarefirst-classtypes:theycanreturnanotherfunctionasareturn-value
o Cantakeanotherfunctionasoneofitsarguments
Swift– Functions&Closures
Ref.CN5E,NT@UW,WUSTL20CS5530
• Aclosureisablockofcodethatcanbecalledlater(anonymousfunction)
• Codeinaclosurehasaccesstoo Variablesandfunctionsthatwereavailableinthescopewheretheclosurewas
created,eveniftheclosureisinadifferentscopewhenitisexecutedo Youcanwriteaclosurewithoutaname(functionname)
} Surroundcodewithbraces{}} Use‘in’toseparatetheargumentsandreturntypefromthebody
¨ Indicatesthatdefinitionofclosure’sparametersandreturntypehasfinished,andthebodyoftheclosureisabouttobegin
Syntax:{(parameters)->returntypein
statements}
Swift– Functions&Closures
Ref.CN5E,NT@UW,WUSTL21CS5530
o Concise1:iftypealreadyknown,youcanomittypesofparametersand/orreturntype.
o Concise2:canrefertoparametersbynumberinsteadofname
Swift– Objects&Classes
Ref.CN5E,NT@UW,WUSTL22CS5530
• Classeso Aswe’dexpect.o Use‘init’asinitializer/constructor.
o Use‘deinit’asdeinitializer /destructoro Instantiationbyreferencingclassnamefollowedby()
} var shape=Shape()
Swift– Objects&Classes
Ref.CN5E,NT@UW,WUSTL23CS5530
• Classeso Toinherit,subclassesincludetheirsuperclassesnameaftertheirclassname,separatedbya:} classSquare:Shape
} classViewController:UIViewController,UITextFieldDelegate
o Methodsinasubclassthatoverridethesuperclass’simplementationaremarkedwithoverride} Overridingamethodbyaccident,withoutoverride,isdetectedbythecompilerasanerror
Swift– Objects&Classes
Ref.CN5E,NT@UW,WUSTL24CS5530
o Properties canhave‘getter’and‘setter’methods.} SimilartoJava,C#,VB.Net
} Note‘newValue’isimplicitlydefinedforusasthenewvalue(seecodeexample)
} Canbeexplicitbydeclaringthesetteras:¨ set(<parameter_name>)
¨ set( mySide ) { ... }
¨ Thereisnotypedeclarationneededbecausethepropertydefinedit.
Swift– Objects&Classes
Ref.CN5E,NT@UW,WUSTL25CS5530
o Inheritance} Class:parent
} Overridewith‘override’keyword.
} Callparentmethodswith‘super.’keyword.
Swift– Enumerations&Structures
Ref.CN5E,NT@UW,WUSTL26CS5530
• Enumerationso Use‘enum’tocreateanenumeration
} Swiftassignsrawvaluesstartingatzeroandincrementsby1,butcanchangethisbyexplicitlyspecifyingvalues
o Canhavemethodsassociatedwiththem.
Swift– Enumerations&Structures
Ref.CN5E,NT@UW,WUSTL27CS5530
• Structureso Use‘struct’tocreateastructure.
o Supportmanyofthesamebehaviorsasclasses,includingmethods&initializers.
o Structuresarepassedbyvalue!(classesbyreference)
Swift– Protocols&Extensions
Ref.CN5E,NT@UW,WUSTL28CS5530
• Protocolso It’sbasicallyan‘interface’fromotherOOlanguages.o Use‘protocol’todeclareaprotocol.
o ‘mutating’indicatesafunctionchangingthestruct.} Notneededinclassredefinitionsasclassmethodscanalwaysmodifytheclass.
} Neededinstructurestoindicatethatthemethodwillmodifythestructure.
o Classes,enumerationsandstructs canalladoptprotocols.
Swift– Protocols&Extensions
Ref.CN5E,NT@UW,WUSTL29CS5530
• Useextensionstoaddfunctionalitytoanexistingtype
Swift– ErrorHandling
Ref.CN5E,NT@UW,WUSTL30CS5530
• ErrorHandlingo RepresenterrorsusinganytypethatadoptstheErrorprotocol.
o Use‘throw’tothrowanerrorand‘throws’todenoteafunctionthatcanthrowanerror.
Swift– ErrorHandling
Ref.CN5E,NT@UW,WUSTL31CS5530
• ErrorHandlingo do/catch
} Indoblock,markcodethatcanthrowanerrorbywritingtry infront
} Incatchblock,theerrorisautomaticallygiventhenameerrorunlessyougiveitadifferentname
} Canprovidemultiplecatchblocksthathandlespecificerrors
Swift– Comments
Ref.CN5E,NT@UW,WUSTL32CS5530
Let’sPractice!
Ref.CN5E,NT@UW,WUSTL33CS5530
• Printstrings(useterminator:””todisable\n)o letlabel="Thewidthis"o letwidth=94o print(label+String(width))o //comparewithprint(label+String(width),terminator:””)
o letapples=3o letappleSummary ="Ihave\(apples)apples."
o letoranges=5o letfruitSummary ="Ihave\(apples+oranges)piecesoffruit."
Let’sPractice!
Ref.CN5E,NT@UW,WUSTL34CS5530
• Q1:What’swrongwiththefollowingcode?
• Q2:
SwiftResources
Ref.CN5E,NT@UW,WUSTL35CS5530
• Contentwasusedfromthesewebsiteswhereappropriate.Thesesitescontainquiteabitmoreinformationandwouldmakeagreatresourceforyou.
https://developer.apple.com/
https://itunes.apple.com/us/book/the-swift-programming-language/id881256329?mt=11
https://www.hackingwithswift.com/read
https://www.hackingwithswift.com/example-code