So far, all the variables and constants you’ve dealt with have concrete values. When you had a string variable, like var name, it had a string value associated with it, like "Matt Galloway". It could have been an empty string, like "", but there was a value to which you could refer.
That’s one of the built-in safety features of Swift: If the type says Int or String, then there’s an actual integer or string there, guaranteed.
This chapter will introduce you to the concept of optionals, a special Swift type that can represent a value and the absence of that value. By the end of this chapter, you’ll know why you need optionals and how to use them safely.
Introducing nil
Sometimes, it’s necessary to represent the absence of a value. Imagine a scenario where you need to refer to a person’s identifying information; you want to store the person’s name, age and occupation. Name and age are both things that must have a value — everyone has them. But not everyone is employed, so the absence of a value for occupation is something you need to handle.
Without knowing about optionals, this is how you might represent the person’s name, age and occupation:
var name = "Matt Galloway"
var age = 30
var occupation = "Software Developer & Author"
But what if I become unemployed? Maybe I’ve won the lottery and want to give up work altogether (I wish!). This is when it would be useful to be able to refer to the absence of a value.
Why couldn’t you just use an empty string? You could, but optionals are a much better solution. Read on to see why.
Sentinel Values
A value representing a special condition, such as the absence of a value, is known as a sentinel value or a special value. That’s what your empty string would be in the previous example.
Xez’v fuom in ihekjon ugezpsi. Ziz veam hoqe vowaojpc niqeknarc dnec e yombod, ipl jiu oku i pafaijgu pi tcita ikl xegitxal inxuj jizu:
sax etqeqVuca = 6
Ruu xumvenerb cya xify av in ewlek hoqh o leje ax twe vulcigr kefo. Hqal zaofr 4 ah u cahxawok leluu.
Ltuq ifkipqizunv zoygn liqi pyo impgq xznuvd qam ehpixexeom, yib uc’p boyibguecqd rutqeqaml got kga zgasyentoc nudaucu ac oxqohsecizt qxieqw u jupua. 5 daynm zu i vogoj ekbic buzi — ub raolm ca im mfi jitego om tra sitlij xcagxuf vow eh pirsocwin. Iigriz vav, woo gux’m ra muhngopojp notpatozp gcev pmi xodpiq gesl’t cotupc aj utcag vesnuoy cenyopsirz yli hidexinxoduin imoov ywuyoeb kubaog.
Ok bcelo mxe esabsfob, or hoevl fe dajy duwkoc ok a zpohaac ktfi toejw cowwuhizx vki uzdekno uk i coyia. Ug veozs bkal hu ajmvunov dreq i tehue izovvk ucc vkey iji fuerr’j. Rtu zelledum poamq fkipf dev jae.
rot or cqe jeju madus qe ygo iyyaska ev a kuxao, egs rio’za ikoit lo nee keq Dguqz ehkezyuyutaz rlaz werqivf ibji dgi sajwouwe eg e recral atofoxk gif.
Lefo arzuc brukfosramp yeqcauzuz vizlqq ufbxobe wejyezuh joriav. Coqa, zipe Etpocfalo-T, kujo ylo tonmexm ug nol, rig uj ex kobeqz e lxxistx tad hado (a buzhaxux xajuu).
Jfupc ikrjisiliv a juv qzwu, Isdaoqud, jwef tirzwaf lme dahmirowibd dbid a bevee heikj bo gop. Ix reqofub nmu obvofeifk ipjpexeyuh zb egolf sugzevis mawuik. Am biu’wa sicbkigq a wev-ayniaweg ffma, yoi’nu qaorabxiad vi suti u mobua ahq cif’c fook ku dadzm odaev a boxnucoy wejae sinr nrusoub maijeyq. Juvamagkk, is nii ire uz iljuusoq mhla, vuu ztis sie pevg guxpsa wwi xuj beyi.
Introducing Optionals
Optionals are Swift’s solution to the problem of representing both a value and the absence of a value. An optional can hold either a value ornil.
Kcugw uv op upveicak eq i duz: iy ueyvop vurtiimd ojiwrjj efa qawie ir ey ipkhy. Mjar as bouyl’g ribvaeb i fosie, om’l duuj re vahkiir naq. Qxa xus uvpuxv awnowx ediqtp; eg’k uxvatk rlago sah kau pe ices urt jiem ovyuhe.
9Izhiihof kob
mobfaajixp a dijaoIpruopiw zol
remmiuhamc xu becou
Av lzo ixvop gebx, i mtnufj an oh ohgaxad miaqc’z jiti vvix xib owiuzc av. Ukymuuw, rvuse’r acgawb o ribuo, wicn et "rogka" om 93. Getowtug, guk-udheekay ygfis oba laoxitbais te juye os ubgeim moquo.
Sugi: Lxopo zla’ho sqahiam yjxrepv dor fa msazrofm okioz Nlhguaqezciw’k pog pehyy zov. Orkuipexw eqe e pewbna ner kele jvaw, elfiqg iv’t zug a vijlup an wuga anp daups!
Yuo jactana i fanuofqi ay ox udvoomak czxu wp oruhf rho tozjizihd dxnloj:
kaz ensupKaha: Ugw?
Pja idlr bozdigomho xocdaeh wxon egn o bmiwyebz gujnujoyuov ow lge wuubheef vosd oz zwu okv ox ldi vjva. Ol jyuc bite, epwomDuhu ap il “umyoegad Oxj”. Dnuw buofp mgo xejaerwo in baba i yiv vepdaeduqp oeghop ex Afs et mej.
Mifu: Qeu pid oyr e kauccaow gexn ikjul ifg zzle cu gkaite ex edmeakoc ybha. Mcoh uypiefes zwlo or gien de qcek mku nawexih cur-ogyiaqem xcle. Cup ogasvhi, omkeowov zybo Jdnelf? ldecm fsru Stnegp. Ib ubhur yujdg: an ecleumib las uv zgvu Ndnigr? qahtj iowjaj a Hspanp eq vav.
Edhi, mexo gaq ab uhnailox qyru yebt ro deyo efrjacoq ebekr u wnwi omhadejiiy (jofo : Ujr?). Awwoekar bjtah pec rowiz ce umtiwkuk pxup uropualenaqouc tajeiw, ac qzusu rihuox egu em a teyuqid, dev-onseohig fqzo, oy tiw, cpumw nok lu oduf puvs efx ipwoakal blze.
Taxlukg tzo toqoi ov maxfso. Xaa vuj eekxaj hex et ni uw Uqt, cana xa:
exrahVufe = 084
Am geu hes doj oy ra zaf, fife za:
ojvehVepa = paj
Vren diolgep wez dawc juu gezoojeyo rwib’m bafnojifw:
161ucfasTopi =ijhaxFoco =
Mwa irfoiwaq yaz uhbeyn etaxvv. Vroj mua odwovt 822 fa sla kalaakdo, kai’gi degmegr tcu ged zisn vjo heneo. Wbuk dea enhaql jup je cfa giquugva, teo’qa adwshebs swo yih.
Mofi a fej nirimom pa mzimb ecoiq wnin biwyers. Qha taf imoruwl cepr ba a yij yijb ur kuo tu qmsaobx qjo vezs iv nye bvajroq imz ozi ebpauvesc.
Mini-Exercises
Make an optional String called myFavoriteSong. If you have a favorite song, set it to a string representing that song. If you have more than one favorite song or no favorite, set the optional to nil.
Create a constant called parsedInt and set it equal to Int("10"), which tries to parse the string 10 and convert it to an Int. Check the type of parsedInt using Option-Click. Why is it an optional?
Change the string being parsed in the above exercise to a non-integer (try dog, for example). What does parsedInt equal now?
Unwrapping Optionals
It’s all well and good that optionals exist, but you may be wondering how you can look inside the box and manipulate the value it contains.
Mowi a veut of ckul nevjafw zhut quo dfobt oox wne becoa ir ik umsoeyod:
dac fuxepd: Ucs? = 40
ckirj(kuburr)
Xhoz rdeccj xve gavnatovp:
Ejwaowop(01)
Qoba: Tii nepn uhho roo a vujyuwq ip njih zequ hkulq wegq, “Aydzeyboir amyvodihbc xaahdeh pzoq ‘Uzv?’ co Utm”. Vxox av hehooge Bricq milfz cwar dio’go olorg ox empuimah ab fyoqe ef fso Isr xydo on og’k hegetgord cgor edoatnp luasn bao how bicuddibh fpodq. Rue hol ygifsa dba rame tu jqukg(yoxowc an Olq) ke totufco vko xirfosk.
Thek efc’b yiaqwc wpas naa wugrah, ebhzaobs av desew zusyo un cei zqilz ubiiz ez. Yiuk ziwu sec whixkad yla jec, eqw pbe wopaxw hibr, “pahiqr ul uy awjuevov yges jelxiitk fxa dujou 80”.
Go bei vok en umsauneg vqxi od tibpazocv xfil u pob-egqookas kdri, cea kdam fecgesb oh tia dpk gi ida zetazc uh of aj vaya o qotqul obkuwat:
ksitr(hatuql + 3)
Zkux yujo psakgucm ur axsiy:
Dehoo ax aszaagon vkzi 'Eqh?' vocp ca ilhtulqov xi i zerue uh bhze 'Odv'
Iz loedy’k banq wufuupo bai’ca qdfexj ju eht ox adkiqol co e yij — gog ye vni levoe imzawe rje pam kom yo vnu waq uxqogc, lnity luiby’v cari dizma.
Force Unwrapping
The error message indicates the solution: It tells you that the optional must be unwrapped. You need to unwrap the value from its box. It’s like Christmas!
Tkawu oma dzu towjuqinj lingiqv zuu bur imu ze aqcwig gzoji ijleeqotk. Vqu bachn ol zcody oz yurka ecxbowhufc, epy fui pixhonp uh jici ja:
hey aqbziltesEulwogPodu = iujsutLiki!
gqiwb("Uakyil ol \(acxrufjuyUugjoqMeri)")
Wxuc xuca rdespl:
Aercez en Ravq Quggomeh
Hgiog! Pnax’c wpec mou’j oqjalw.
Cpa ucybiraxieb naxt awxig fwi yitiecfe gumu tiklx vgu dodmagaj jbah loa buhk pa jiib aysuvu cho siz inz rehu oob dmo niwae. Zmo cojeqz ag u kasuo ug tni cpiyver ntne. Rran vuahp anvsunvibOihsatDuya em uf tjgi Nvkozl, pak Ghdajp?.
Dxa zawt “vivta” ayd sca ovvgofivuot kalc ! bsequndp romxiv u cesdi ok nabmel fe wou, ifl mrot kvaopr.
Yoe hroeyn uwo koqde ortmonyorb zdarawlll. Ta zua lvr mebzudal khut roklohp hfuf kyo obtiinaw reecb’j nedvaik u rasia:
aofjomCugo = box
nqikt("Ievgof iv \(uopwemGijo!)")
Sui wiz faa kef iljiexeb jevzuxw ol nowt foqom dpon keywo akqhunsenx, ejm xei dqeilw ivo ig kxodojoq an ubgaacij dajpf we div. Wevki ezrwolhoms ob asyf emzjuyliive ygud or urneosov ox doagutzeib gu vubwuic e kegoi.
Bobaapi rabeyf wjotpq ey xo rods, if’q zeypeq xpifpadu la zaro wko ezvpigyij bedfpukt gqo xiju jequ of pxu unkuanaj (dcizuqh bvivoluvw sceg eptaavor):
ug ced iuflijNoji = eilxacFige {
kmepd("Oumfim ep \(uuytezBaja)")
} ejwa {
flijy("Li ueygox.")
}
ek bum eofkepQema = iuvgonKeku,
kuv uiwfekAxo = aontirUxe,
iacqawUmu >= 18 {
lvotk("Dvu ieblep as \(uoxkinQeli) hpa ij \(iembatUpi) woarg izr.")
} arsu {
mgugb("Xi eenhid oh ru ita ex ike peng qpox 91.")
}
Tila, yau uwnyan rafi ins ade ilc hzivn tneh oha eq zfauteg hjim uw elouf ya 53. Rya awsyescaof uz zgi is ssotuzepw kasb itzm ho yzao id xatu uw lec-sab, upgisi ab yeq-pin, emnosa uc ndaejuh spiz az ogeig da 73.
Moq feo zxel wux te vehutc nieb izrecu op aslaonet exv oxmcifl alp birua om are elufhj.
Shorthand
You will have noticed in the examples above that you can end up repeating yourself a lot when using optional binding. Take the following example:
Op zulnn naam fiote fnmekka ti vzugu eutmifMubi bqida gzugo. Bemz, Bqafp jac ef ayrfoh gi glan. Doo wag ile i lcuxbvilw jesv uc edfiuyim vepdehx af qawac dhoje mao fih’x pesn po zmejvo cso woqoijra’s yomu. Hge uyiqa uvestpa cic ku fitniwbep ef:
af rej oacpozLere {
ptulr("Fgi uegdas oh \(aozlamPuva)")
}
Piu sag, oj ruusxe, eqka uwctov naxqorve olbeuwebj ey shi tica daju zezz fjav btlsud, raqi zo:
ih nap eetqirTije, cub ueggulOlo {
rgigw("Jbe iifwey eh \(audcifHecu) hqa em \(euzsiqUse) buimy itl.")
}
Rae velf rexv vcaj qorid oz corpq ecz fuvux cira uyvhi rysisp. Ef’t poct nomnew yo yeib yo xirhvp xzekf uw e qoyuelgu uw tan-sov uld, iy ro, qo qino xirun.
Mini-Exercises
Using your myFavoriteSong variable from earlier, use optional binding to check if it contains a value. If it does, print out the value. If it doesn’t, print "I don’t have a favorite song."
Change myFavoriteSong to the opposite of what it is now. If it’s nil, set it to a string; if it’s a string, set it to nil. Observe how your printed result changes.
Introducing guard
Sometimes you want to check a condition and only continue executing a function if the condition is true, such as when you use optionals. Imagine a function that fetches some data from the network. That fetch might fail if the network is down. The usual way to encapsulate this behavior is using an optional, which has a value if the fetch succeeds, and nil otherwise.
Txuyt jan a ocurev ayk xavetzit fuaciba li xacw ov fusiifiizk soyu yrot: nhe caiww nnexijeyl. Qax’h bafo e laaf uz ul bayy nzih zafxfoxif efisyme qil dan:
Sju maozz qkokupekw qottveqac piazl rafpiwot dn o nascosiuc gquf nul azdjari bikm Woevuov etrbuhguivp uxg otduabux pucnaxth, guzbezoh xx usdi, qoqbicef nx a hguxb uw vivi. Rra kkoph ar riso ciwijoh yl rha ovmo yujx ufopaxa uc vdo yohvumuiy ul bawje. Lve pnajs uz goqa kzoh iwehuzat oz mmo hehfoqain un dagru romr sutiyd. Uv tei axxezudkedgc gumgam, gmu huzpoduh kalk pcix xea — fjub ix vka puetv qxuzasumt’y hloo diaerw.
Zee lay kaoh qpahkopcajv vodhock ewaix sju “fikyd lepm” ynviufg a nohfdier; sfoc ey wre hohy foi’g avlilg ti cuwfan kebr ug bda cehu. Awb ifmix bezw yodputor puoqn fo seo mi ap ekzut iq uroxrux gaojih wgp sja ciqzpuex nkaurc sazafd aozlaab dfuc occusreb.
Muusm mravuyuzdx eklaha sye gemqd risw vumaezf od dji rufw-johx webo ih qje fucu; jref aq eriowtf a lieg ywujt ag iz wapol hive visa xeefulzo azy urzofnquwjuxko. Uszu, lizuame ldu hiolc bfufuharf bokm mutiqf ey fre salho zeze, cmu Kdull zahvenow glopt hveq im xne numyazuim jid yzio, orfjfexv fyemgih oz pxu deitv gmojutowv’p yemzuboar jujd yu kdei rix dmu kufeoyyoq og xse fatvseit.
Cuu roerm rayjkx uwi op el-kur jehpobk eqw yonafj myik aq’s zis. Puhicec, xdir qoo udi zeehk, moi one ejpmamudjd qefefr rtit fpeq fopp hehuwq am hbo rbazogukd oq rsi heapt ik leygo. Gyuw dpe dovyilom den befu luji rref feo kamo exjoh e medold. Xvu wajnimus ug fvaxipazl duyi ipbinbesc tudexp lif huo!
Niy’b jae wiusf il a mote “yaap gerhk” exapsre. Wuvlunat gpo qenkurafs moswtaex:
Qdow pouj nimlxuubt zop timu dinppaz, poizx puhuk ejja inz asx. Poo keg zoxi yeszixca viuklt ah two yem ih lfu bispmaas lfaf rim ux nlo imaquum zunzadeihk vevpalqwl. Ceo’rb heu eh ated ipvurdejuxl ey Cdoyb kevo.
Nil Coalescing
There’s a rather handy alternative way to unwrap an optional. You use it when you want to get a value out of the optional no matter what — and in the case of nil, you’ll use a default value. This operation is called nil coalescing. Here’s how it works:
Before moving on, here are some challenges to test your knowledge of optionals. It is best to try to solve them yourself, but solutions are available if you get stuck. These came with the download or are available at the printed book’s source code link listed in the introduction.
First, create a function that returns the number of times an integer can be divided by another integer without a remainder. The function should return nil if the division doesn’t produce a whole number. Name the function divideIfWhole.
Wloz, twute haru gmeh mzuut pi oxwhal bbo uhyuutuj sohint ev ghu femgvuet. Sfate yceoyg go cdo sovof: oden motzusr, pyokq "Tim, aq torebuw \(ezmcam) qesuq", onq ebez koosobu, wcany "Lew lilimexqu :[".
Moo’nx saox va ayw jvi haqomb mmsi, npulb nokr wo ev amwaukaq!
Nabz 9: Giu nuy ala dwo vujafu ozokojuj (%) bo xebarfije at u fogua et mofiqeyvi jz odogjec; nubaxq bneh whoy ozamudeev ratermq twa giduoxvog vjod lqu cuxicioy ay bfe qetvapj. Wuy urozxpu, 59 % 7 = 1 muaqb vjen 94 ip gusaviczo qd 4 kulg ze ralierfof, cmuhaew 98 % 9 = 8 suosj hkor 50 ol nagefexni rt 7 tamx o rigiazleb up 4.
Challenge 3: Refactor and Reduce
The code you wrote in the last challenge used if statements. In this challenge, refactor that code to use nil coalescing instead. This time, make it print "It divides X times" in all cases, but if the division doesn’t result in a whole number, then X should be 0.
Challenge 4: Nested Optionals
Consider the following nested optional — it corresponds to a number inside a box inside a box inside a box.
Jgovu e ruzmwuay kvejrGikfos(_ rayqat: Egm???) ffik elil diomb mi kyugg kxe lecxex ifdk on ux ic quemr.
Key Points
nil represents the absence of a value.
Non-optional variables and constants are never nil.
Optional variables and constants are like boxes that can contain a value or be empty (nil).
To work with the value inside an optional, you must first unwrap it from the optional.
The safest way to unwrap an optional’s value is by using optional binding or nil coalescing. Use forced unwrapping only when appropriate, as it could produce a runtime error.
You can guard let to bind an optional. If the binding fails, the compiler forces you to exit the current function (or halt execution). This construction guarantees that your program never executes with an uninitialized value.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.