WelcometoSwift
AboutSwift
Swiftisafantasticwaytowritesoftware,whetherit’sforphones,desktops,
servers,oranythingelsethatrunscode.It’sasafe,fast,andinteractive
programminglanguagethatcombinesthebestinmodernlanguagethinkingwith
wisdomfromthewiderAppleengineeringcultureandthediversecontributions
fromitsopen-sourcecommunity.Thecompilerisoptimizedforperformanceand
thelanguageisoptimizedfordevelopment,withoutcompromisingoneither.
Swiftisfriendlytonewprogrammers.It’sanindustrial-qualityprogramming
languagethat’sasexpressiveandenjoyableasascriptinglanguage.Writing
Swiftcodeinaplaygroundletsyouexperimentwithcodeandseetheresults
immediately,withouttheoverheadofbuildingandrunninganapp.
Swiftdefinesawaylargeclassesofcommonprogrammingerrorsbyadopting
modernprogrammingpatterns:
Swiftcodeiscompiledandoptimizedtogetthemostoutofmodernhardware.
Thesyntaxandstandardlibraryhavebeendesignedbasedontheguiding
principlethattheobviouswaytowriteyourcodeshouldalsoperformthebest.
ItscombinationofsafetyandspeedmakeSwiftanexcellentchoicefor
everythingfrom“Hello,world!”toanentireoperatingsystem.
Swiftcombinespowerfultypeinferenceandpatternmatchingwithamodern,
lightweightsyntax,allowingcomplexideastobeexpressedinaclearand
concisemanner.Asaresult,codeisnotjusteasiertowrite,buteasiertoreadand
Variablesarealwaysinitializedbeforeuse.•
Arrayindicesarecheckedforout-of-boundserrors.•
Integersarecheckedforoverflow.•
Optionalsensurethatnilvaluesarehandledexplicitly.•
Memoryismanagedautomatically.•
Errorhandlingallowscontrolledrecoveryfromunexpectedfailures.•
maintainaswell.
Swifthasbeenyearsinthemaking,anditcontinuestoevolvewithnewfeatures
andcapabilities.OurgoalsforSwiftareambitious.Wecan’twaittoseewhat
youcreatewithit.
VersionCompatibility
ThisbookdescribesSwift4.2,thedefaultversionofSwiftthat’sincludedin
Xcode10.0.YoucanuseXcode10.0tobuildtargetsthatarewrittenineither
Swift4orSwift3.
N O T E
WhentheSwift4.2compilerisworkingwithSwift3code,itidentifiesitslanguageversionas
3.4.Asaresult,youcanuseconditionalcompilationblockslike#ifswift(>=3.4)towrite
codethat’scompatiblewithmultipleversionsoftheSwiftcompiler.
WhenyouuseXcode9.2tobuildSwift3code,mostofthenewSwift4
functionalityisavailable.Thatsaid,thefollowingfeaturesareavailableonlyto
Swift4code:
AtargetwritteninSwift4candependonatargetthat’swritteninSwift3,and
viceversa.Thismeans,ifyouhavealargeprojectthat’sdividedintomultiple
frameworks,youcanmigrateyourcodefromSwift3toSwift4oneframework
atatime.
SubstringoperationsreturnaninstanceoftheSubstringtype,insteadof
String.
•
The@objcattributeisimplicitlyaddedinfewerplaces.•
Extensionstoatypeinthesamefilecanaccessthattype’sprivate
members.
•