CS5530 Mobile/Wireless Systems - College of Engineering...

35
Ref. CN5E, NT@UW, WUSTL CS5530 CS5530 Mobile/Wireless Systems Swift Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang UC. Colorado Springs

Transcript of CS5530 Mobile/Wireless Systems - College of Engineering...

Page 1: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

Ref.CN5E,NT@UW,WUSTLCS5530

CS5530Mobile/WirelessSystems

Swift

YanyanZhuangDepartmentofComputerSciencehttp://www.cs.uccs.edu/~yzhuang

UC.ColoradoSprings

Page 2: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

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…

Page 3: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

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.

Page 4: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

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/

Page 5: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

Xcode Playground

Ref.CN5E,NT@UW,WUSTL5CS5530

o Aninteractiveworkenvironmentthatallowsyouupdatevaluesreal-timeandseeresults.

o A‘project’optioninXcode.

o NewforiPadiOS10!!!

Page 6: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

Xcode Playground

Ref.CN5E,NT@UW,WUSTL6CS5530

Page 7: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

Swift

Ref.CN5E,NT@UW,WUSTL7CS5530

• Quickoverviewofthelanguageo Assignments

o ControlFlow

o FunctionsandClosures

o ObjectsandClasses

o EnumerationsandStructures

o Protocols

o ErrorHandling

Page 8: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

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

Page 9: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

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.

Page 10: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

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.

Page 11: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

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

Page 12: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

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.

Page 13: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

Swift– ControlFlow

Ref.CN5E,NT@UW,WUSTL13CS5530

• Switch

Page 14: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

Swift– ControlFlow

Ref.CN5E,NT@UW,WUSTL14CS5530

• Switcho letcanbeusedinapatterntoassignvalue

o Noneedtobreak} Onlyonematch

Page 15: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

Swift– ControlFlow

Ref.CN5E,NT@UW,WUSTL15CS5530

• for-ino Iterateoveritemsinadictionarybyprovidingapairofnamestouseforeachkey-valuepair.

o Dictionariesareunordered!

Page 16: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

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 { … }

Page 17: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

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

Page 18: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

Swift– Functions&Closures

Ref.CN5E,NT@UW,WUSTL18CS5530

o Cantakevariablearguments,collectsintoanarrayforyou.

o Canbenested.

Page 19: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

Swift– Functions&Closures

Ref.CN5E,NT@UW,WUSTL19CS5530

o Functionsarefirst-classtypes:theycanreturnanotherfunctionasareturn-value

o Cantakeanotherfunctionasoneofitsarguments

Page 20: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

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}

Page 21: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

Swift– Functions&Closures

Ref.CN5E,NT@UW,WUSTL21CS5530

o Concise1:iftypealreadyknown,youcanomittypesofparametersand/orreturntype.

o Concise2:canrefertoparametersbynumberinsteadofname

Page 22: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

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()

Page 23: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

Swift– Objects&Classes

Ref.CN5E,NT@UW,WUSTL23CS5530

• Classeso Toinherit,subclassesincludetheirsuperclassesnameaftertheirclassname,separatedbya:} classSquare:Shape

} classViewController:UIViewController,UITextFieldDelegate

o Methodsinasubclassthatoverridethesuperclass’simplementationaremarkedwithoverride} Overridingamethodbyaccident,withoutoverride,isdetectedbythecompilerasanerror

Page 24: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

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.

Page 25: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

Swift– Objects&Classes

Ref.CN5E,NT@UW,WUSTL25CS5530

o Inheritance} Class:parent

} Overridewith‘override’keyword.

} Callparentmethodswith‘super.’keyword.

Page 26: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

Swift– Enumerations&Structures

Ref.CN5E,NT@UW,WUSTL26CS5530

• Enumerationso Use‘enum’tocreateanenumeration

} Swiftassignsrawvaluesstartingatzeroandincrementsby1,butcanchangethisbyexplicitlyspecifyingvalues

o Canhavemethodsassociatedwiththem.

Page 27: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

Swift– Enumerations&Structures

Ref.CN5E,NT@UW,WUSTL27CS5530

• Structureso Use‘struct’tocreateastructure.

o Supportmanyofthesamebehaviorsasclasses,includingmethods&initializers.

o Structuresarepassedbyvalue!(classesbyreference)

Page 28: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

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.

Page 29: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

Swift– Protocols&Extensions

Ref.CN5E,NT@UW,WUSTL29CS5530

• Useextensionstoaddfunctionalitytoanexistingtype

Page 30: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

Swift– ErrorHandling

Ref.CN5E,NT@UW,WUSTL30CS5530

• ErrorHandlingo RepresenterrorsusinganytypethatadoptstheErrorprotocol.

o Use‘throw’tothrowanerrorand‘throws’todenoteafunctionthatcanthrowanerror.

Page 31: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

Swift– ErrorHandling

Ref.CN5E,NT@UW,WUSTL31CS5530

• ErrorHandlingo do/catch

} Indoblock,markcodethatcanthrowanerrorbywritingtry infront

} Incatchblock,theerrorisautomaticallygiventhenameerrorunlessyougiveitadifferentname

} Canprovidemultiplecatchblocksthathandlespecificerrors

Page 32: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

Swift– Comments

Ref.CN5E,NT@UW,WUSTL32CS5530

Page 33: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

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

Page 34: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

Let’sPractice!

Ref.CN5E,NT@UW,WUSTL34CS5530

• Q1:What’swrongwiththefollowingcode?

• Q2:

Page 35: CS5530 Mobile/Wireless Systems - College of Engineering ...yzhuang/CS5530/spring2017/slides/swift.pdf · Swift -Overview CS5530 8 Ref. CN5E, NT@UW, WUSTL •“Don’t need to import

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