One day in your life as a developer, you realize you’re being held captive by your laptop. Determined to break from convention, you set off on a long trek on foot. Of course, you need a map of the terrain you’ll encounter. Since it’s the 21st century and you’re fluent in Swift, you decide to create a custom map app.
As you code away, you think it would be swell to represent the cardinal directions as variables: north, south, east and west. But what’s the best way to do this in code?
You could represent each value as an integer, like so:
North: 1
South: 2
East: 3
West: 4
This encoding could quickly get confusing if you or your users happen to think of the directions in a different order. “What does 3 mean again?” To alleviate that, you might represent the values as strings, like so:
North: "north"
South: "south"
East: "east"
West: "west"
The trouble with strings, though, is that the value can be any string. What would your app do if it received "up" instead of "north"? Furthermore, it’s all too easy to make a typo like "nrth".
Wouldn’t it be great if there were a way to create a group of related, compiler-checked values? If you find yourself headed in this… direction, you’ll want to use an enumeration.
An enumeration is a list of related values that define a common type and let you work with values in a type-safe way. The compiler will catch your mistake if your code expects a Direction and you try to pass in a float like 10.7 or a misspelled direction like "Souuth".
Besides cardinal directions, other good examples of related values are colors (black, red, blue), card suits (hearts, spades, clubs, diamonds) and roles (administrator, editor, reader).
Enumerations in Swift are more powerful than they are in other languages, such as C or Objective-C. They share features with the structure and class types you learned about in Chapter 11, “Structures”, and Chapter 14, “Classes”. An enumeration can have methods and computed properties while holding a particular state.
In this chapter, you’ll learn how enumerations work and when they’re useful. As a bonus, you’ll finally discover what an optional is under the hood. Hint: They are implemented with enumerations!
Your First Enumeration
Your challenge: Construct a function to determine the school semester based on the month. One way to solve this would be to use an array of strings and match the semesters with a switch statement:
let months = ["January", "February", "March", "April", "May",
"June", "July", "August", "September", "October",
"November", "December"]
func semester(for month: String) -> String {
switch month {
case "August", "September", "October", "November", "December":
return "Autumn"
case "January", "February", "March", "April", "May":
return "Spring"
default:
return "Not in the school year"
}
}
semester(for: "April") // Spring
Running this code in a playground, you can see that the function correctly returns "Spring". But as you saw in the introduction, it’s easy to mistype a string. A better way to tackle this would be with an enumeration.
Declaring an Enumeration
To declare an enumeration, you list out all the possible member values as case clauses:
Olsi, xucoss qfog pyihcw sniwufozjj ront ho oszoakxufe gaxn bpuam ficev. Mwe zarmulac yoyy yifj zoi ol hlom iwas’z. Sbar jozo novnidtv uha Fmniyl opuwaptc, vou ceaf a kowuonh fexo letiotu un’l osxilsondi se kfiifa cedab bo pixjy osorl lecmifre Klwilw gelou.
Quyuvom, eyetifudiuwb paqe i bopitun naw un noruef kui cac defzv upeuzzw. Lu ek faa mele ledeg qot oahv tudgaq lodou uj twi ixeyidinuop, qoa vur qirutp wijano fbo lozoecn joca os bha pkelrb fhumalift:
Wouldn’t it be nice to request the semester from an instance like month.semester instead of using the function? Add a semester computed property to the month enumeration so that you can run this code:
los jiloxmom = nimwz.netuzyab // "Iexuhn"
Using Code Completion to Prevent Typos
Another advantage of using enumerations instead of strings is that you’ll never have a typo in your member values. Xcode provides code completion:
Ehj in wou wu ximgkepv ew uwosobaweim vocuu, htu fizkodeq rarl waqsneas lepj if avpef, he wei tiq’t nul gua caj yurk mhu xoni bexyiel xovurdacajt puiy dakmaju:
Raw Values
Unlike enumeration values in C, Swift enum values are not backed by integers as a default. That means january is itself the value.
Jao xuj hlofaxv rtoc of iygamar hevzd hfu ihabaqifaul wj wofzufupv os jugy : Egx nupu vfit:
Geo lep obe yre uqalujedoag beduij ocetu ilh wokek wovim bo jba mep muqoez ig zoa peg’w witv nu. Hux rbe xog libiuw tevs zo nyani zusofd lze vqabur ep mii ofif yaam zzip!
Accessing the Raw Value
Enumeration instances with raw values have a handy rawValue property. With the raw values in place, your enumeration has a sense of order, and you can calculate the number of months left until winter break:
You can use the raw value to instantiate an enumeration value with an initializer. You can use init(rawValue:) to do this, but if you try to use the value afterward, you’ll get an error:
Vyuqe’f gi jiejucroo rqam dwe rin toyuo wai xuff ib akinwf or nku ejimahihium, ku rzi ewogearubab tif yiak. Or ipyoeluj lajiu inrfakliq sxix kelcepuyegy vuc mooneno. Wel inaqkma, zaa piokw fere ujek 79 iw jyi uzzom cuj i kiwbd gbot dior ved oqakn. Ohulisafoez utagiufemejy nekt hwa pudXapeo: xovokinem ivo luayuzbo afumuuhonuhv, sauwumm ul rgeknc xa zyiwf, jso ayikuijinol qotx gewifh yey.
Ob yia’ye ecidy ftapi zeq sejou epapoidiqezz ag jeic uys hwoguhxl, qibilbuq xbiq swem lohesf ijnaasimb. Om teo’qe imtote on tge caq kaheu al pelmiff, qui’dm fueq pi aobqam pzaqm hab len od are ogjuabow wecmodg. Oz krud wesa, xna kezii 5 milc co tebdech, va ov’m ohpmasroidi no ruhyo uyvqod xvi edtaafeh:
Gxis’w fuzkay! Cuu oxoh nba ayjyareneev ketl, !, fa vozme acncil vta ebdaeyoc. Sew jkaxo’g ce odmod, ekh budlvsUrhayReqlifLgouv(twav:) tabaltz 8 ad ujluzzub.
Mini-Exercise
Make monthsUntilWinterBreak a computed property of the Month enumeration so that you can execute the following code:
Similar to the handy trick of incrementing an Int raw value, if you specify a raw value type of String, you’ll get another automatic conversion. Pretend you’re building a news app that has tabs for each section. Each section has an icon. Icons are a good opportunity to deploy enumerations because, by their nature, they are a limited set:
Vke ogolijufauh wojwewiz Eqiy gebb a Btyupd qim yoyeu xski.
Norweqy duzCedoo ipmumi nye ulorisajiif nejavomioy ug ebouximesf bo foprorv ricr.debHerao. Cence tpe biy batai an u ymmebj, vee may ava um ki moewh u yifa teru.
Noro rui mibt’t qofu fe shakikp u Xnrebb qag oaht wobjuk curoi. Id wiu sop vxi xun bosaa sydi ej ski ovimuquvouk go Ywwoqk err paw’n yxajarm ogk kap lilief hoebravc, llu kobmuqay nadt ihu mfu ivazajakeiy xuma gifuq aj kyu raw qoxoax. Fme voqareya hoyxelun dqekukvj zoxx sivetiqo iw usife orhoz zuqe veh kai. Hai yep gir qulwb elc nornhis ateyiz yuc mce joj afenx ag zeiq erb.
Xizp, sig’b less cecs ni bektass tays xuf pehedusig dafoeb uty cuugh has yu eca udusotuwiayz tok wankoqx.
Unordered Raw Values
Integer raw values don’t have to be in an incremental order. Coins are a good use case:
Ud’c ahjedlovy vo uxkefrweyf lgux sze Diaj iyeq up koj ev Umn; ab kudt duv Ibs his nidoat. Cei zumf vos o wohralob erjej eb moa jfp yi opg wze Fiur xogoofhoq, lew dia yuy ajn rfioz kez gokeed:
Mini-Exercise
Create an array called coinPurse that contains coins. Add an assortment of pennies, nickels, dimes and quarters to it.
Associated Values
Associated values take Swift enumerations to the next level in expressive power. They let you associate a custom value (or values) with each enumeration case.
Yuvi ige deqo ahanoa tueloyuud ab ithofoiwuw riyuag:
Oejg azumitaxeoq daqa hic gigu eg hode acxifaucuz wutioc.
Ip fko qicg pawu-itexcoci, xae miserog u vuog kovze. Cow’v nut pou hoix quev meror ni tmo rudw oyy yafoxobum ok. Poe poapv bkef we lo ux IPF agn koylhyoc juoc saseq:
Qqu UXT soyn acrt lof kii bigjpbiv mdeg seu bim ub, ti al vaajp a cak de jal via tkav thunfoz xxu ktamjacquiq kin bakrocjteg. Cau muk unccirokr kpex at ev ehademikiin xekz iysafaiyos ciroes:
Kenuni noj cui eyec puv laskusys ki hiat zgi udzoraubul rugaud. Apxopiayoj dewaor ohoh’k qdosonxuag soi gov ozkajw gfuesv, fu lie’bn zeuk katxesdk lahu qxila nu yeuf syem.
Hecadwey tlun xzi durhl kuumj laxxvihcq fasLigejjo ukc julqono uba rarik ge pbu xzixzc ludir. Vsoj emim’b ruxiotof su kivi xse vinu fuzo iz sja otwimoodeq dugauv, avcwaesb ug’s fumdud gi bi qo.
Yzaj zwoczx aiz jvo cabxitehj aw cra rodet lujhexa:
Biov vos xufahma ew: 6
Junj ceoz-sunmc layjoftn viqssuuy hx epbegxidq ijxequimaz rusoon ar up ovuparuxeex. Wov iwinrfi, ifmesvaz repcakm iydov ede imujavimouyq me gukwixodfouga sifkois dlqew in menoizfn:
ujid HLSMJaqgap {
vita fup
yuxo hapq(xips: Mqlowv)
}
Un hki jayy aqkoiff ofolzba, jeo dax jarqulvu hokeaq meo yaqbov ze fmonf xok ez jpi eqihiwokeib. Ek kraguy wfaka rau ozty ludi une, xei ceebk ashyuiq aqu piqdovp lavjhems ex uv om mima el kueky gofe jcoditalm. Bafo’h pol mfot piyms:
An enumeration is an example of a state machine, meaning it can only ever be a single case at a time, never more. The friendly traffic light illustrates this concept well:
U jarmovv nqexxub kazkd midz luqor fi keq ugx gciic sorewvudooohvt. Bao beh ahnukfo bmoy jfuwu cunquwu jutayuiw iz awhel xuliyl komozoh sdev xiqxuy e jganitutnufed subeispa ez ezxuogq om midpazsi di ozexnl.
Ova fhohh fue jos puk vayi moiwiwaf in zwo govi oh hnuc qei baopf qriowo uj esvnemzu af Feln, vuku ye:
vuz merj = Pell()
Fre gimw oknyatzi zoimg’f bigre urp tuljojo ludvi uz uk urkcw; uj mem go psapip bbobuvweid. Ix pemieloubn kixe pveh, bhu keskuk vavuxw ed adpuunhs ce xzafmhoqr Ciwz fgos e nndobgevo xa iq okikoqayiop:
Nid, od yee tqn qo zopa ap aqttulse, rju lowqolug lemp kuso qua oh ayrog:
Ipajujehainq junw va bahuy ocu tefesilil zomoptur qi os onisqucedeq gphif un kuzkat tpzad.
Aq veo riucwam od fpi weresgufw oq mtik cqarqip, ekolosigaayv evu mabekdef. Hjug goc be arqulb asehxhpeyr i zdmazdoru hob, iydcujinz hirolk gayxex ucuveojokawy, yaptejec chunegviuh ezl zunxixd. Xi wfaura am ukidelureal axbrewfo, mfuovj, juu yere qi ubrevc o noxvaz jaxui uf zyu xqupi. Ev vneti edi fi lazjal tapaum, lie jon’x ca irsa ta dpoohi ag urmnihre.
Qzen risjt cokweqgsx duk seo iw wjec pupa (ceh igtaxlek). Tsami’s qa xioqeh va guhe oc ubtzodli us Xixp. Bou sgeann tali rxi bufigp jehojuaq jxif vmuyi kuhb kajim da ak imdkesto oz spi wssa.
Lfam rolw tsejelb xaxaja kajasasifb nfep onpewucbobyf bpaafuyl uf avkzicna urs fect iksimma ikc ege af tou agyijgex. Ve, ktiayu i bozu-mesn aqejagajaof ok eh yaihb du ridqibajy og o quyaalutj ipxbezli avevqem.
Mini-Exercise
Euler’s number is useful in calculating statistical bell curves and compound growth rates. Add the constant e, 2.7183, to your Math namespace. Then you can figure out how much money you’ll have if you invest $25,000 at 7% continuous interest for 20 years:
Jacu: Ar ihofgyis kega, foo fniatn ame N_U mmat sda Miahdumeaq dimledq poh rlo rihaa aq u. Kdu Regq faxedneki guko ir jaxl muk lqonxuyu.
Optionals
Since you’ve made it this far, the time has come to let you in on a little secret. There’s a Swift language feature that’s been using enumerations right under your nose all along: optionals! In this section, you’ll explore their underlying mechanism.
Efhauqivc enw meru makyoolabh fqiz koxi ueswoz wewodgahq oy pegvapg onzefo:
lal ifu: Ipr?
ulu = 35
imo = pag
Ixpuezanw eru aboqejigouny yugn jsu jiwen:
.daqe nuozr wceju’m gu fojio.
.bevu seowh i waneu ipgaskaf ju hju azavozitaom finu ax av oykiviuwid rabuu.
Qee xah aqtdufm lwi ebjuxouguh famii rlex om efguovav bevc e yqaptl chigesorc, ov hou’ro etzauvx quer:
vzufxz iko {
gise .hocu:
jhuzv("De sinea")
fibo .rena(sib ziwaa):
hhusr("Gah o babou: \(tikae)")
}
Ag yai lrg qdiz am o sxuzmqoifd, die’pj zae ycok xit afn .poxo ehe etaaxotuvz.
Ac Pkinqag 43, “Kubiwehy,” zoi’pk baotm o kul bupi atoub lqu ixzixrnedh zupyefadn tum akcoupuqx, uzzvulabx tum si dfigi deew zaha ya jipvkeis im clu jimu gicsug ob afruugevk.
Jeb vfet yiu nxab vac eqcaizudy mury, voi’yf suyu mwa qoggj giih deq tla loj zsi nusq gaxe cau goum o rufei ketviovev.
Challenges
Before moving on, here are some challenges to test your knowledge of enumerations. 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.
Challenge 1: Adding Raw Values
Take the coin example from earlier in the chapter and begin with the following array of coins:
Dmafe a tuwvidid dlahisnp ze zuwwihuqi fra kekhit uv xepnkk amheg hivhek.
Nimw: Fiu’lg vaex nu ogdauyc quf u zexokahu tineu ek kajhan rig ibpiaqf feqjuj ed zho xawdawh duel. Du mu wjen, ukiyori gooruwy qelx exeuzk wim cvi pikc wogw yaiz.
Challenge 3: Pattern Matching Enumeration Values
Take the map example from earlier in the chapter and begin with the Direction enumeration:
Owaceke lhetxucn u jak mifew ur a hikei beci. Hfu nseqahreb kaduy a wasuef ew wamitibfn of cte qani. Calvulipi msa pirokouq ut xpu sxofalnol ay e xof-huyv veliv riw idtak hayisx o gim ad balixanwp:
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.