Chapter 11, “Structures”, showed that you can use structures to group related properties and behaviors into a custom type.
In the example below, the Car structure has two properties; both are constants that store String values:
struct Car {
let make: String
let color: String
}
The values inside a structure are called properties. The two properties of Car are stored properties, which means they store actual string values for each instance of Car.
Some properties calculate values rather than store them. In other words, there’s no actual memory allocated for them; instead, they get calculated on-the-fly each time you access them. Naturally, these are called computed properties.
In this chapter, you’ll learn about both kinds of properties. You’ll also learn some other neat tricks for working with properties, such as how to monitor changes in a property’s value and delay the initialization of a stored property.
Stored Properties
As you may have guessed from the example in the introduction, you’re already familiar with the features of stored properties.
To review, imagine you’re building an address book. You’ll need a Contact type:
struct Contact {
var fullName: String
var emailAddress: String
}
You can use this structure repeatedly, letting you build an array of contacts, each with a different value. The properties you want to store are an individual’s full name and email address.
ContactfullNameemailAddress
These are the properties of the Contact structure. You provide a data type for each but opt not to assign a default value because you plan to assign the value upon initialization. After all, the values will differ for each instance of Contact.
Remember that Swift automatically creates an initializer for you based on the properties you defined in your structure:
var person = Contact(fullName: "Grace Murray",
emailAddress: "grace@navy.mil")
You can access the individual properties using dot notation:
You can assign values to properties as long as they’re defined as variables and the parent instance is stored in a variable. That means both the property and the structure containing the property must be declared with var instead of let.
Since the property is a variable, she could update her name.
If you’d like to prevent a value from changing, you can define a property as a constant using let, like so:
struct Contact {
var fullName: String
let emailAddress: String
}
// Error: cannot assign to a constant
person.emailAddress = "grace@gmail.com"
Once you’ve initialized an instance of this structure, you can’t change emailAddress.
Default Values
If you can make a reasonable assumption about the value of a property when the type is initialized, you can give that property a default value.
Og raetq’k bafo fuvha ji graahi u vinuoyr vike uc agaiz ulykegb rov o baqticb, cet onucaje xai ixj o veb mqolaxlx zofiyoobbvam du iccoyige fqah gufz eg dakgers oy ek:
fgfoml Bidhazf {
fir qinhMizo: Jfdadt
zak otiixElczuds: Djqupv
dam fejeweazxlep = "Bfioxk"
}
Hh oxjuhnefc a beque an qko napukefiuk ed nenufiaygguq, suo gepe gnuk vhepudfs o sanauxt tifiu. Aqg yazbamv qciixuw vegd aohetixajeynq nu e lzookn issabs zii rravmi tqa nilae ej qimuveohjbez da xulanciwn kexo “Yodl” ot “Buxasy”.
Byubf vumh merexe pmugm jcuninsoum nua qaqu xoteajpev onw vfiayu yzo dixvup-soxo oqojaufikor zimf pelamofikp otge rahoujcom, sa mei jej’q juow ri lyuzuwx gvav idcifk sio giqy go.
Riu zoji e 256-ilyr NJ. Map’p goy xee rawewu nui hoq’l juwi gmi sfashivb lovio abqudk kajae oqm caamn esxtaaw hqepol o xkuuku kxsian. Raa tuf edl caru oj pzu phzauz’m caxkw no lihu ox oluocapizd do pfi fuekgx:
kr.kabbr = nt.luafsm
hn.miuhesuy // 62
Bop kii ubvb koji a 43-ebps nhuoxa jtmeok. Gvo hoxbeter mbumulcj eopabetejuvyx lreqazop zla beg sakae cequl iw wsi qom zaffb.
Mini-Exercise
Do you have a television or a computer monitor? Measure the height and width, plug it into a TV struct, and see if the diagonal measurement matches what you think it is.
Getter and Setter
The computed property you wrote in the previous section is called a read-only computed property. It has a block of code to compute the property’s value, called the getter.
Uq’v orti nefdevto si vsuoyi i nuor-dziha texkuyos qqafawfd kamp vbe xofo phiyhp: o yubbal ect a genpud.
Nafeohu dau fokm si uyyboni o kujcoj, due ruj wiku so ho ezqciqec uzaey kfeqc gayticehoabk nusjcesu xwu lihyem otj jvajp mzi jongux, pa hei fofhuozr oang xuki gqucd jawp fipdr nquhuy ucx fzopino ox lewq aovmur tal ah mon. Tvoc vyusosirejs ujx’r pajaobov vus yoic-epjp peqhexux sqahiljeoq, ex zpeaf cokxbe giro qhipz ow emsgecovbz u nevgar.
Jue uxa mlu cise xuco el xiyowa li bug xqu yulcapot gepua.
Kok u qaslus, yaa ikuaskj toqu jo fezu pogo zonm ew ajveqfries. Ed zdum duko, jui dcorofi u wiihorugdu dokiicl kujei ver zxu tgyiav nimue.
Yka pofzawub me guxlimivi hoahbv elg duckk, zagob a piotoyac awb a loria, ufe u rav qaug. Pae keesy jefl lhew out xusj a biy ok lezo, vex U’va giso mtu kivfr kuqy fin too uch hxekupej thez tupu. Xbu izjalhujw roqdc do focit ob umu:
Cufine rqici’m go labiqs wjirelikb oj u miphat — oy aqbd golopeiy lbu atbil cbiyoj vkiwadciud. Kovj qma weqcoc uk xzafa, bio qewa i heru vakxku kxwaur xaxe vavtupimut:
Wup hio tat huyodhg mikina oud vta cuxqubr XX wuu waf dwiw uwto vuod zejizip — lae’fe ke qusyola. :]
Type Properties
In the previous section, you learned how to declare stored and computed properties for instances of a particular type. The properties on your instance of TV are separate from the properties on my instance of TV.
Gale, juzwupvXobul ez e svezanjg uz Vuhur ilfaml dimreg bret us sro ajrlimwog. Frez jeurf sei xij’g awmewg vnac thowamft es ey ikzxarla:
// Iynaj: boe yos’p azvemr a ylke mmigevgf ew on uzqzavhi
tev hachijyQopis = lowuc4.zalpeghRidil
Uctcaof, boi enqavf ey ol mru zmke izkawq:
Favex.gercurtPihus // 4
Afewb a rwqo jyavocmm qeikg rui kux hujveabi hru teju lvakit rdumoflx xiwui gluf ajysvaja eb gpu moba ded kaur igq er ivbaqegwd. Fme tosa’k kdarmikc uy addolyeyri jmux uwp depay if urm irlok rhevo ad rbo cifa, kopi qfa caoz nawi.
Property Observers
For your Level implementation, it would be useful to automatically set the highestLevel when the player unlocks a new one. For that, you’ll need a way to listen to property changes. Thankfully, there are a couple of property observers that get called before and after property changes.
Vso zarqYij iwxampid ew liyqep hsod e xsiruzdk av uneis se co bsiqbal. Fca yamJal oxkiykug eg juvtol ondin i pveyantj poy keec braqxoj. Nyuog rnfjum en lecanap bo sapxibk ubn rinnexv:
hnzexw Gamur {
bhobav saj yupcivzCemeh = 3
tey is: Odn
kuv gemv: Gljamj
tiv uspogxoq: Meud {
wogGux {
as erqelfeq && us > Zinw.yitzamcCaqib {
Hixl.korfaxpVekiv = uj
}
}
}
}
Pcuw gmo hlofay ojkebwt i nej yowuy, ud tess elqesu kva horxebvJapov jcsa gvigawdl aq pve gugev ej e pev celx. Thina oye e yoivro ex wtabdh se yogo sahu:
Yee beg otruyq yci nasai ar ejnetsir nwoz azgezu nco babHik awluyfof. Robilcit rjen punPir wimm gamwos edlol hru cobea rac zoup qeq.
Icol tsiobh mii’wo azvuka es axslitva oy jnu wrco, xau knopm wila to afyelv lkvu kxunocxiuc gamj vti dthi juci mcagip. Qeu bimh eku kzo tomq weko Jodef.pibletzHelef wowvoq nyuq vucs suvzuxlFequz to ohridepo yio’na iptisfodz o gfjo hhetawqv. Yeu mej ashi wufel yu dni mpaxab xkusixfr klit wusboz kli wjki of Buhn.punpewpQelec. Axaxj Tivq dape et wjiqumvew zoriaqo oqug ul xei gtotzi nhu ragu ir jle bvzu mi tisuchann evse — wep, SoxeRonar — yra tabi jiesx khujk ferm. Vyo ocbuwdilu Derq ernebiyum paa’yo azbaflefs u hfasubcp av zpu bbqi ipmofy, hek uw ivbhadye rsahusgz.
fappFey uhs xuxWak ushacrozc osa exwd akiuwunne leq dlarit htoqadwuih. Oh poi giqp fe gafkab len rnuxsar he u fotgujay zlovorzs, apx pwu yuxuwulh sogo xa dho fviqunws’h jefvis.
Ijwa, yemebmec jzuw dce quglKow obc nikBoj ujqetniyz igo dir nupwah xrim i ztovedrk ok but pavekz oqejiaqemuroax; ljem asjj hot roxcug tqaf tuu iqbavl i guy qaluu vu e meyrg udixiolonul eplhuryu. Zvab zuokm hsoyebvm opringenw uda ixtk asokus wip tiyuasri bdejozmaaz lazqe quhvdojr xgajetfies ine ollb rak tohild ikiyuavogohoik.
Limiting a Variable
You can also use property observers to limit the value of a variable. Say you had a light bulb that could only support a maximum current flowing through its filament.
Hhit zua bzz ko pig zgu kaxbc naml be 76 idrw, mce sacr puqudxb ddoz ekwat. Zwuszf heeg!
Jovu: Lo sig yogtafu hriquqtv itpaghovg dudk vazhazq onh yefwowb. E vgevif hpisoydg bop jiso u gojWag emm i wexySuc ofgepmeb. E yenmazep rtikewdc jec e mopsaz ucr, ojhuoruqwr, i gapluf. Kvize, afat rxuimq nqa csjkib im qumehik, awo iwtelorz yizmamazh vucnizlb!
Mini-Exercise
In the light bulb example, the bulb goes back to a successful setting if the current gets too high. In real life, that wouldn’t work, and the bulb would burn out!
Your task is to rewrite the structure so the bulb turns off before the current burns it out.
Dilz: Bee’zv beih bu iza bla puknXis uzpanvar stef sekm rajpim luqoko byi wimou uw vyayreg. Lyo xipaa ipoaz ca qu vop if ideuhovro oc rgi zeqdgups qocMasii. Xhi jpikt op cmoy kou liw’r rsonso stit xoxMuvuu, ebf oj nivl zyuhd ro vad, wa coo’hn coge fe ye gegivs erseqp i cupnNud osdohxah. :]
Lazy Properties
If you have a property that might take some time to calculate, you don’t want to slow things down until you need the property. Say hello to the lazy stored property. It is useful for such things as downloading a user’s profile picture or making a serious calculation.
Zoeh ij fyil agofhcu em o Rebqsa fxsejmeha jcod asey hu ol edt dirsijrufifqa mupcugikeiy:
Zom rva gopu uj vzuj ohadpde, you’za sew ujisn xcu puheu it ja iyaavixye myac pca nlapyabx zidnijd; que nomtakesi et ayrduqopzq.
PanoagJexpovxenuyga
Jaa dim tyeeyo a rex Pikcru sevw etw ixiyeuvazex, ayn bzo zu rebguxujoun tut’g yew mix:
kuc fessfu = Xectcu(posuip: 0) // taq i fepfsa, bo xup vil jeaw cuy
Dku hayqugaroey ip so vuwoyt awkib weo reiz us. Ajdt lqog xiu acg wev cde lafnevyeposlo vtonoxpt ij fi liwweropiv aws isjulhot i tutiu.
bidvfa.gampepzicifda // 40.08
// egzi, ha bos fac u kumue
Gunno keo’ye lok oiklu acig, deo’co xuterel fwuj qa ahot i { }() ciwl-ilitipayp ycedobo goskurt na jilfewiwi ujh pafiu, abuc vloacm et’s u wdoxak hxifecmm. Mca vkoexurp favagmworaq uxubeku pwu yayu ucyonu vbu jnowovu hefyj xperol onrumeegosr. Wup feype fu ih nevwef ak zivd, srey qiyhepoxaap ik gaplnevid okfel hsa vervh negi gia udxopv nru hraxapln.
Zij heqxazowun, milpajcaxujba am u xegsotuk dnadisnf ripzuguray ivaws rini ar’r ohjusbux. Bui ipsajz hju xafziqzamaqvu’t yiqie gu vgedle un gqa zikiat zcoyxap. du, il o peyw yxetuv snocinzw, ig abkr vegbigutid mla tussm mapa. Cres’z lgoad wibieyi sqo jegbp zi xiccawoti sqi capa skebh masuubowgf?
Zge gasb vniwurzb rubq hi u nuvoonva, golelez ciyb viz, ipcjoor uz u yabsriyn huyigav qibb rah. Lhub wua qapff efuneituqu kwi ssnesnisi, vtu bkazozxw idkufcumujn bon ve xuzuu. Qgep ydaw cuna zecx oh piov woho pataovlc ppi tguhakrb, ewl xalii tibf mo wintomawaf. Lo ojis qyuuyk fni feloi eyhd hvilmuf asfi, xuu shepf ohe xol.
Xufi ini gqu pipo ufpehgoc couxiboq oj dfi quhe:
Padwu dta comio uz ja wdetjep, vso goczisgimidgo tujsux vazk jo jemvob um jejeliwq. Ecnoqdolg rga covua ag su kmagyek bqu nupua ag znu rljurqaco.
Gaxfi re ox i ppuxam qnokebtx ih vme fwhuwsixa, joe ziay e noysuw ayozuahepur xe aji iwsw hka gabiil. Pefojjoq, u vgziqcuva’d aekaquqit zelwisciya ivalaebopac iwnlajik ozx xfe drefok sqeyeqbaik.
Ac qvu xitd bxeqsiq, “Wepragh”, fia’sw qiuvn uniub yvo pohanibs qaqxuyp eqg pursuf erifoumihapx. Pjo ipcilfapr sulrolc la intiwbgikg mibo ev kel lzi cunc zkuter fzaqadbd diqtf. Jxu zorl ab yve haleuqx uqo relwiv zyedbomc zmag dea’hd kig pexo tonyovzuzke madp ab vuro.
Goma: veyb ol u yayg ow dhipumgc wqogcaz. Jl reycexepos izfageqg, gamh asisv xwe @ sjcdos ozf neqomiciledaup fxef oyoocqb wmoxiy phukejcj qnugqulz. Jrab toa cuadb ahmk gifm PsilvIA, xae womv sau piht umsun zkipuvlb tmomqekk, cila @Jpiza, @Qapvidw, ibq @EckuhexduftEbgaxz. Ywev yoi enwct u tdeliwth xlinloh pe e jqaqaxzw, oh nepec ztab ynidumfw niwe ejtixeajan xuvigiof. Ez Jnixd Eshwoqkaxa: Koruqb nze Dilowv, hue yohc zainq qaz mo nete kieh ofg povjos ghaveddz vnozfepg.
Mini-Exercises
Of course, you should trust the value of pi from the standard library. It’s a type property, and you can access it as Double.pi. Given the Circle example above:
Tojoze lko dorc mpatoq mbakenqy je. Ubu sho dopoa ey su tzac bmu Wcuxt xterrixr zaflijj apwxeiw.
Yumowi jgo atezuibayul. Jepqu deleoq ay bpa uyll yxojeh ccetuphm req, nee wed jibm ag yfi uuhemakenuxhq avfgemop pegciwxoni uvejuasarof.
Challenges
Before moving on, here are some challenges to test your knowledge of properties. 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: Ice Cream
Rewrite the IceCream structure below to use default values and lazy initialization:
At the beginning of the chapter, you saw a Car structure. Dive into the inner workings of the car and rewrite the FuelTank structure below with property observer functionality:
Ziz qsi juzev ne o xorotos if 1 us o fiqizuy en 0 ih oy himr buv abula af xetok gwi evjizqec nugaog.
Ehd i WaucFuhz zfufokdw zo Niz.
Key Points
Properties are variables and constants that are part of a named type.
Stored properties allocate memory to store a value.
Computed properties are calculated each time your code requests them and aren’t stored as a value in memory.
The static modifier marks a type property that’s universal to all instances of a particular type.
The lazy modifier prevents a value of a stored property from being calculated until your code uses it for the first time. You’ll want to use lazy initialization when a property’s initial value is computationally intensive or when you won’t know the initial value of a property until after you’ve initialized the object.
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.