Академический Документы
Профессиональный Документы
Культура Документы
AbsoluteBeginner'sGuidetoSwift
AbsoluteBeginner'sGuidetoSwift
Update:WereexcitedtoannouncethatTreehousehaslauncheditsLearnSwiftcourses!
LearnSwiftbasics,Swiftfunctions,andbuildtworealappswithSwift.Learnmoreaboutour
Swiftcourses.
WhySwift?
Incaseyouhaventheard,ApplejustintroducedanewlanguageforiOSandOSXdevelopers
calledSwift.IthascometolightthatSwiftwasintheworkssince2010,whichis2yearsafter
thefirstSDKwasreleased.ApplesawthelimitationsofObjective-Cwhichisalmost30years
oldanddecideditwastimeforachange.However,intrueApplefashion,theydidnotwantto
releaseahalf-bakedlanguage.TheyrealizedthatnomatterthedrawbacksofObjective-C,they
couldstillpushtheenvelopewithit,andsotheydid.
ItsbeensixyearssincethereleaseofthefirstSDKand1.2millionappshavebeensubmitted
totheAppStore.Millionsofdevelopershavesufferedthroughlearningthearcanesyntaxand
limitationsofObjective-C.Recently,avocalfewdecidedtospeakupexpressingtheirwoes
abouttheoutdatedlanguage.
Swiftprobablytookalittleoverfouryearstocreateandistheresultoftheworkofmanysmart
individualswholovecraftinganewlanguage.Theylookedallaroundforinspirationandnot
onlycreatedanewlanguagebuttoolstoalongwithitthatwouldmakeiteasytolearn.
WhentalkingaboutSwift,Applereferstothreekeyconsiderations:Safe,ModernandPowerful.
Itlivesuptoallthosethreethings.Outlinedbelowaresomeoftheverybasicsyouneedtoget
upandrunningwithSwift.Ifyoualreadyknowaprogramminglanguage,thenyouwillseea
lotofsimilaritieswithothermodernlanguages.Youmightevenwonderwhytheyhadtoinvent
awholenewlanguage,butthatisdiscussionforanotherblogpost.
UsingSwift
Firstly,youwillhavetodownloadandinstallXcode6.Onceyouhaveinstalledit,openitup
andselectFilefromthemenu->New->SelectSourceontheleftundereitheriOSorOSX->
Playground.Giveyourplaygroundanameandyouarereadytogetstarted.
Alternatively,youcouldusetheREPL(ReadEvaluatePrintLoop)fromtheterminal.
Instructionstorunfromtheterminal:
1.Openupterminal
2.IfyouhavetwoormoreversionsofXcodeinstalledthenyouwillneedtoselectXcode6as
http://blog.teamtreehouse.com/anabsolutebeginnersguidetoswift
1/10
2016/5/27
AbsoluteBeginner'sGuidetoSwift
yourdefaultversion.IfyouareonlyrunningXcode6thenskipaheadtostep3.Ifyouareonly
runningXcode6thenskipaheadtostep3,otherwisegoaheadandrunthefollowingline:
sudoxcodeselects/Applications/Xcode6Beta.app/Contents/Developer/
AtthetimeofwritingthispostbetaversionofXcode6wasnamedXcode6-Beta.Please
checkyourappnameintheApplicationsfoldertowriteouttheappropriatepathwhen
usingxcodeselect.
3.TostarttheREPLtype:
xcrunswift
Fundamentals
Variables
Aswitheveryprogramminglanguageyouhavevariableswhichallowyoutostoredata.To
declareavariableyouhavetousethekeywordvar.
vargreeting:String="HelloWorld"
Theabovecodeinstructsthesystemthatyouwanttocreateavariablenamedgreetingwhich
isoftypeStringanditwillcontainthetext,HelloWorld.
Swiftissmartenoughtoinferthatifyouareassigningastringtoavariableandinfactthat
variablewillbeoftypestring.Soyouneednotexplicitlyspecifythetypeasintheabove
example.Abetterandcommonwayofwritingtheaboveexamplewouldbe:
vargreeting="HelloWorld"//InferredtypeString
Variablescanbemodifiedoncecreatedsowecouldaddanotherlineandchangeour
greetingtosomethingelse.
vargreeting="HelloWorld"//InferredtypeString
greeting="HelloSwift"
Whilewritinganapplicationtherearemanyinstanceswhereyoudontwanttochangea
variableonceithasbeeninitialized.Applehasalwayshadtwovariantsoftypesmutableand
immutable.Mutablemeaningthevariablecanbemodifiedandimmutablethatitcannotbe
modified.Theypreferimmutabilitybydefaultwhichmeansthatthevaluesarentgoingto
changeanditmakesyourappfasterandsaferinamulti-threadedenvironment.Tocreatean
immutablevariableyouneedtousethekeywordlet.
http://blog.teamtreehouse.com/anabsolutebeginnersguidetoswift
2/10
2016/5/27
AbsoluteBeginner'sGuidetoSwift
Ifwechangeourgreetingexampletouseletinsteadofvarthenthesecondlinewillgiveusa
compilererrorbecausewecannotmodifygreeting.
letgreeting="HelloWorld"
greeting="HelloSwift"//Compilererror
Letstakeanotherexamplesoyouunderstandwhyandwhentouselet.
letlanguageName:String="Swift"
varversion:Double=1.0
letintroduced:Int=2014
letisAwesome:Bool=true
TheaboveexamplenotonlyshowsusthevarioustypesthatareavailableinSwiftbutitalso
showsusthatthereasontouselet.AsidefromtheversionnumberoftheSwiftlanguage
everythingelseremainsconstants.YoumightarguethatisAwesomeisdebatablebutIlllet
youreachthatconclusiononceyoureachtheendofthispost.
Sincethetypeisinferredweshouldsimplywrite:
letlanguageName="Swift"//inferredasString
varversion=1.0//inferredasDouble
letintroduced=2014//inferredasInt
letisAwesome=true//inferredasBool
Strings
InouraboveexamplewehavebeenwritingtheStringtype.Letsseehowwecanconcatenate
twostringsbyusingthe+operator.
lettitle="AnAbsoluteBeginnersGuidetoSwift"
letreview="IsAwesome!"
letdescription=title+""+review
//description="AnAbsoluteBeginnersGuidetoSwiftIsAwesome!"
Stringshaveapowerfulstringinterpolationfeaturewhereitseasytousevariablestocreate
strings.
http://blog.teamtreehouse.com/anabsolutebeginnersguidetoswift
3/10
2016/5/27
AbsoluteBeginner'sGuidetoSwift
letdatePublished="June9th,2014"
letpostMeta="BlogPostpublishedon:\(datePublished)"
//postMeta="BlogPostpublishedon:June9th,2014"
Inalltheaboveexamples,Ihavebeenusingthekeywordletwhichmeansyoucannotmodify
thestringonceithasbeencreated.However,ifyoudoneedtomodifythestringthensimply
usethekeywordvar.
OtherTypes
BesidesstringsyouhaveIntforwholenumbers.DoubleandFloatforfloating-point
numbersandBoolforbooleanvaluessuchas:trueoffalse.Thesetypesareinferredjustasa
stringsoyouneednotexplicitlyspecifythemwhencreatingavariable.
AFloatandDoublevaryinprecisionandhowlargeofanumberyoucanstore.
Float:representsa32-bitfloating-pointnumberandtheprecisionofFloatcanbeaslittleas
6decimaldigits.
Double:representsa64-bitfloatingpointnumberandhasaprecisionofatleast15decimal
digits.
Bydefaultwhenyouwriteafloating-pointnumberitisinferredasaDouble.
varversion=1.0//inferredasDouble
YoucanexplicitlyspecifyaFloat.
varversion:Float=1.0
CollectionTypes
Array
Collectionscomeintwovarieties.Firstly,anarraywhichisacollectionofdataitemswhichcan
beaccessedviaanindexbeginningwith0.
varcardNames:[String]=["Jack","Queen","King"]
//Swiftcaninfer[String]sowecanalsowriteitas:
varcardNames=["Jack","Queen","King"]//inferredas[String]
http://blog.teamtreehouse.com/anabsolutebeginnersguidetoswift
4/10
2016/5/27
AbsoluteBeginner'sGuidetoSwift
Youcancreatetwotypesofarrays:anarrayofasingletypeoranarraywithmultipletypes.
Swiftiskeenonbeingsafesoitpreferstheformerbutcanaccommodatethelaterwithgeneric
types.Theexampleaboveisanarrayofstringswhichmeansthatitisasingletypearray.
Toaccessanitemfromthearrayyouneedtousethesubscript:
println(cardNames[0])
Note:weusedafunctionabovecalledprintlnwhichwillprintthevalueJacktothe
consoleandthenaddanewline.
ModifyinganArray
Letscreateanewarraythatcontainsatodolist.
vartodo=["WriteBlog","ReturnCall"]
Makesurethatyouusethekeywordvarsothatwecanmodifyourarray.
Toaddanotheritemtoourtodoarrayweusethe+=operator:
todo+="GetGrocery"
Toaddmultipleitemstoourtodoarraywesimplyappendanarray:
todo+=["Sendemail","PickupLaundry"]
Toreplaceanexistingiteminthearraysimplysubscriptthatitemandprovideanewvalue:
todo[0]="ProofreadBlogPost"
Toreplaceanentirerangeofitems:
todo[2..<5]=["PickupLaundry","GetGrocery","CookDinner"]
Dictionary
TheothercollectiontypeisaDictionarywhichissimilartoaHashTableinother
programminglanguages.Adictionaryallowsyoutostorekey-valuepairsandaccessthevalue
byprovidingthekey.
Forexample,wecanspecifyourcardsbyprovidingtheirkeysandsubsequentvalues.
http://blog.teamtreehouse.com/anabsolutebeginnersguidetoswift
5/10
2016/5/27
AbsoluteBeginner'sGuidetoSwift
varcards=["Jack":11,"Queen":12,"King":13]
Abovewehavespecifiedthecardnamesasthekeysandtheircorrespondingnumericalvalue.
KeysarenotrestrictedtotheStringtype,theycanbeofanytypeandsocanthevalues.
ModifyingaDictionary
Whatifwewantedtoaddanacetoourcardsdictionary?Allwehavetodoisusethekey
asasubscriptandassignitavalue.Note:cardsisdefinedasavarwhichmeansitcanbe
modified.
cards["ace"]=15
Wemadeamistakeandwanttochangethevalueoface.Onceagainjustusethekeyas
thesubscriptandassignitanewvalue.
cards["ace"]=1
Toretrieveavaluefromthedictionary
println(cards["ace"])
ControlFlow
Looping
Whatitgoodisacollectionifyoucannotloopoverit?Swiftprovideswhile,dowhile,for
andforinloops.Letstakealookateachoneofthem.
Theeasiestoneofthemisthewhileloopwhichstateswhilesomethingistrueexecutea
blockofcode.Itstopsexecutionwhenthatconditionturnstofalse.
while!complete{
println("Downloading...")
}
Note:theexclamationmarkbeforethevariablecompletedenotesnotandisreadasnot
complete.
Likewise,youhavethedowhileloopwhichensuresthatyourblockofcodeisexecutedat
leastonce.
http://blog.teamtreehouse.com/anabsolutebeginnersguidetoswift
6/10
2016/5/27
AbsoluteBeginner'sGuidetoSwift
varmessage="Startingtodownload"
do{
println(message)
message="Downloading.."
}while!complete
SubsequentcallstotheprintlnstatementwillprintDownloading..
Youhavetheregularforloopwhereyoucanspecifyanumberandincrementthatnumbertoa
certainvalue:
forvari=1i<cardNames.count++i{
println(cardNames[i])
}
Oryoucansimplyusetheforinvariantwhereitcreatesatemporaryvariableandassignsita
valuewhileiteratingoverthearray.
forcardNameincardNames{
println(cardName)
}
Theabovecodewillprintoutallthecardnamesinthearray.Wecanalsousearange.Arange
ofvaluesisdenotedbytwodotsorthreedots.
Forexample:
110isarangeofnumbersfrom1to10.Thethreedotsareknownasaclosedrange
becausetheupperlimitisinclusive.
1..<10isarangeofnumbersfrom1to9.Thetwodotswithalesser-thansignisknownas
ahalf-closedrangebecausetheupperlimitisnon-inclusive.
Letsprintoutthe2timestableusingforinwitharange:
fornumberin1...10{
println("\(number)times2is\(number*2)")
}
Wecanalsoiterateoverthecardsdictionarytoprintoutboththekeyandthevalue:
for(cardName,cardValue)incards{
println("\(cardName)=\(cardValue)")
}
http://blog.teamtreehouse.com/anabsolutebeginnersguidetoswift
7/10
2016/5/27
AbsoluteBeginner'sGuidetoSwift
IfStatements
Tocontroltheflowofourcodeweofcoursehaveanifstatement.
ifcardValue==11{
println("Jack")
}elseifcardValue==12{
println("Queen")
}else{
println("Notfound")
}
Note:Theifsyntaxcanhaveparenthesisbuttheyareoptional.However,thebraces{}are
mandatoryunlikeotherlanguages.
SwitchStatement
TheswitchstatementinSwiftisveryversatileandhasalotoffeatures.Somebasicrulesabout
theswitchstatement:
Itdoesntrequireabreakstatementaftereachcasestatement
Theswitchisnotlimitedtointegervalues.Youcanmatchagainstanyvaluessuchas:
String,Int,Doubleoranyobjectforthatmatter.
Theswitchstatementmustmatchagainsteveryvaluepossibleifnotyoumusthavea
defaultcasewhichmakesyourcodesafer.Ifyoudontprovideacaseforeveryvalueor
adefaultthenyouwillgetacompilererrorsaying:switchmustbeexhaustive.
switchcardValue{
case11:
case12:
default:
println("Jack")
println("Queen")
println("Notfound")
}
Letssayyouhaveadistancevariableandyouaretryingtoprintamessagebasedondistance.
Youcanusemultiplevaluesforeachcasestatement:
switchdistance{
case0:
case1,2,3,4,5:
println("notavaliddistance")
println("near")
http://blog.teamtreehouse.com/anabsolutebeginnersguidetoswift
8/10
2016/5/27
AbsoluteBeginner'sGuidetoSwift
case6,7,8,9,10:
default:
println("far")
println("toofar")
}
Therearetimeswhenevenmultiplevaluesarelimiting.Forthoseinstancesyoucanuseranges.
Whatifanydistancegreaterthan10andlessthan100wasconsideredfar?
switchdistance{
case0:
case1..10:
case10..100:
default:
println("notavaliddistance")
println("near")
println("far")
println("toofar")
}
Canyouguesswhattheabovecodewillprint?
Functions
Finally,wehavebeenusingprintlninalotofourexampleswhichisanexampleofhowto
useafunction.Buthowcanyoucreateyourownfunction?
Itissimple,youhavetousethekeywordfuncandprovideitwithwithaname.
funcprintCard(){
println("Queen")
}
WhatgoodisafunctionifitalwaysgoingtojustprintQueenasthecardname.Whatifwe
wanttopassitaparametersoitcanprintanycardname?
funcprintCard(cardName:String){
println(cardName)
}
http://blog.teamtreehouse.com/anabsolutebeginnersguidetoswift
9/10
2016/5/27
AbsoluteBeginner'sGuidetoSwift
Ofcourse,wearenotrestrictedtojustoneparameter.Wecanpassinmultipleparameters:
funcprintCard(cardName:String,cardValue:Int){
println("\(cardName)=\(cardValue)")
}
Whatifwesimplywantedourfunctiontobuildastringandreturnthevalueinsteadofprinting
it?Thenwecanspecifyareturnitwhichisspecifiedattheendofthefunctiondeclaration
followedbyanarray>.
funcbuildCard(cardName:String,cardValue:Int)>String{
return"\(cardName)=\(cardValue)"
}
AbovewearesayingthatwearecreatingafunctionnamedbuildCardwhichtakesintwo
parametersandreturnsaString.
Conclusion
Ifyouhavemadeitthisfar,thencongratulations!Youarenowwell-versedinthebasicsof
Swift.Thatisalottotakein,butitisonlyscratchingthesurfaceandwhatSwiftiscapableof.
Thereissomuchmoretolearn,andhereatTreehouseweareworkingoncoursestoprovide
youwithalltheSwiftlearningthatyouneed.Staytunedformore!
IfyouwanttolearnthebasicsofSwift,takeAmitsLearnSwiftcoursesonTreehouse.
http://blog.teamtreehouse.com/anabsolutebeginnersguidetoswift
10/10