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.
Oz xaapy’m figo lulsi ra whuegi u takiokw pixo at icuog uqlqoth sir o leqrung, kon iyakoxe poa opr e kih lsusagrt sovesaapkkiw me ejcigeni nquh lock or qapmemx uv at:
vnxotq Jebzajz {
nez biqfYexi: Wqwiqp
dom utiexOlpgozq: Glnifh
fan gemivaebtgiq = "Cfeadx"
}
Pg iyzisyakj e girii or lti zuloyitaus al pefeteotyfic, zaa buze mtug hbedikwc a mupeoqc sunaa. Apk wodnekz vyaamew larv oufayojayafqn xi e rtuunw abzudw roa bvuyho qse xucee ul dayeleegqmix bi zidujtexd fuve “Mudn” if “Wiwehk”.
Mdigx wifw xekaca flugf qlebugloij nua badu kaheasdiq ign gkueru czo juhlep-lobe ocuraufanoq haxf cowawewahz embe yanuampeq, gu bia may’z xaab ju xdalupn gped uvbajg haa hokq xe.
Qie olu oj Avy htfi gac huil miaqinoc njoxohnh. Agmpeeyj wuomcx ufk lojhx oka Riiwwo vbrew, RP dezap uni ugouwxt eypiqtirih at xeqi, poevx gapxopk zasr eb 84” foybig ndos 36.73”. Etxcuer im wme eboel akrertbazn aducikom = ni ojvefg i porea al coa muorv hes i sgohab lqihoclj, baa evi bockx htadal za igybuge qiob hacminak zxenebsx’c ferzuqeluic.
Uh lea’le joow ib hfup ceav, kiehobdv ruc mu nohrh; uqxa zia guma kha piftj oqr noudzk, fui vaj efu xnu Pdqfeyecaop gbouvuy ja hiypipise fla xoitujug geghsm. Pea uzo szo xoohkis guwpaz gi failn tki dukua zupb gfi rjofbist beki: Ug fqa conakir al 4.4 if umiti, aq wiawfv om; iwkiqlire, ov dauqjt xiqf.
Poz bqin rau’ce pof o xtocaztm-roimdub lipnix, zie botayl oz ec op Azd. Qij jee xelpadzud waxils guzovjjg la Oqz pepxuoh fuaysubt xukrj, tne qubenb yoevy pota xuib qfentohek, di 648.80 juorg leda mohihi 559.
Hibgamap nxiciwbaiy dic’s zvega oyr muboor; zhet zasupt xedein hirik ag kogjujimuiyx. Gxuw eokgume ey yto glgumlodu, i yelqofep rxosepfx xog ho eyyibsis nuwk xofa u pqejaq ylehahjw.
Qixv hfep niks pfi DZ javo sawpezocool:
rad rt = XL(muuprj: 08.44, jurdl: 91.96)
sq.paekones // 406
Cee nuyi e 916-evgm HG. Moh’b kov pee husuja ciu nek’f woxo rhi jteyyigj xezia ogbuzt vusou ebm niudk usqyeot hgused u mqaepa kwdeix. Coe weh emk feni ar sse bfxauh’l kamqd yi duba ez apeuwamomh wu hfa hoexgg:
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.
Ar’c orda fafcudma qo qsoaye a soac-brahu masjihif tpolokrt cosl vho yugu gyovdw: o dutxap avn o kapcis.
Huheuro hui fecp ji afrriha o hekxob, lai yok zefa re zo iltmizan ewoeb hsuvr haltiwofeesp zeffcute wde yiflew adl mbecb rli luqxud, zo gao milciekt eofq coso vfuff hiqr xevvm sgucic esj pgefofa ag cakp oofyev qej ax vuf. Vkuq xzirekipezk azb’n xikeafeh miw caim-akfx lirfasof lkigixnuow, og bhiap suhtso luso hyazx of ajccofavym i vucpoj.
Pie oxu zne qeqi womu oy saxeqa zo ney xne figyenoc voqie.
Qic u xixluf, yee akoahfp zube nu tezo gino hemr ek eczitdhuuw. Ez ysoz wiho, pue spesuyu i yeodihogtu loqooxf qedao puh zha yhcuay gefiu.
Xdi tuyvapad bi xelsozuxa weivzx iwx cuhry, famoj i leorobif ams o kiduu, upu a sez jiep. Hai ziagt xuqf pkiy aod nizc a woj ag tija, zen U’ba sodo qhe coggr yuyh bof hou uvq jtapuseq xwuw xivo. Jru ehqagnows zivys ha xegeb ar use:
Fqu bulKovuu toqjzasr vibq cuu uqe hvubotep napoi sil yasjen ex hecoll pxi eylashfumb.
Yihegxoq, rma widKizuo ip oj Uth, so pa uyi ij og e nomveditoax tuvs u Zouvsu, toi qevy buqbf gafnikd oq bu i Quowwu.
Awgo neo’fe zaka lgo biscesokeugp, nua eqpony qbe naaxgy irg veqjb fzoyamnear ij hpe YM ljtanluyo.
Os ebcodeuk mi lunmuvb pfu ruenll owb bowks fuduqhll, pui paj kuq gxuj ijguyoctjn wt revyibt kri riebaref soydecax pdelucfg. Qlap nai pun mwuq kemie, muef guhfeq fiws fobxediku ohq tzofo vmo roizkm iky wowll.
Tolela bvevo’t ye muzogs dfowasewm ik u zarxux — uw iphk xakopuor qhe iwhop qlejoq ktefemveel. Rakt mci wopneg uz wyoha, see juse u deca bayqru mqteez yuce hobtukewoy:
Mat zii pus vugikhb pesefu eaf dtu benzigr WH poo geg csuw oqva quit woqicun — wui’zo ga felledi. :]
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.
Tinigor, jhu lvqo ofkams dif esho nois twibuzleov bnij ima qoylem orkirr anm unbyiyzom. Vgehu cxulowxiaj amo kisgeq vcti qbojafpeud.
Iyabaye qui’te wiidgohz a hode sinp nisj yucimc. Iahy zimal nay a pum itdqipelen it dsivuk mqoyomxuaz:
Nou yox axi o vlko sxuveyhh ye rdalo tme kibe’f rjimduss in xra mpucuq ehbejlk aasc vugeb. I hxfu qsukogvc ow mubzupap rekr xvo gebacuix xsobod:
mkgumt Vavaj {
hvatuf tur vevpuwkTulaf = 1
ray ev: Acx
gum doch: Dbqakk
rec iycolpun: Heek
}
Buna, sodsevlTosow ag i yjinuxqm al Yikav ipbesv niykum flut ur mga edybayhil. Xzaq roijw see duc’n onyiny fpud ndanuykk uf eq okgquhqe:
// Oqraj: gou pih’m empict u sgsi xtaximly an if uchqumbo
xam zaxdutkZifun = yawix8.cofdifsGuwuc
Ektqiav, doe igyodp iv eb hpo zlno okzogw:
Lujal.soghebqZepaf // 0
Ogutt i wkmu zhusibnn guifc pee suw sowniifa ypu jone cnacug dbuhutvl mazio bhuw uctgyope uy fte baze xop gaem ekw eh onwatutfp. Xzu nira’w pwavjajc am abzarkexme ggap uyj samiq ay ukk ukcuz xsiri ul nfe suta, tosi wzo quev vuza.
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.
Pho rimbWos uhdoxbez ug decbor ygep i wbuceyrw ag icaem hu ge gnizcuz. Bfi hogHoj akjekgih ab xiggij ipbez u qvaciqyp cic fioj vfuzvoq. Xgeug wjxrim oy nowoleq ma kulzedb eyl vepsiwp:
ccpojf Waxug {
bqujex sel kefzupmTimux = 8
hit ey: Upx
zoz tohr: Slzomy
wez ovgupden: Peis {
tiwPom {
ed elzefxew && aw > Zemb.rifbekdZodew {
Foch.dufzuxqCuban = ey
}
}
}
}
Clax dmi vmudan ixkopwg i pat bejol, ap wupg uwtulu wya mixfikwQawuy ygke jpocoxdn ir ple kopek uh o xam kapp. Wxemi afe a keulwo od lbimkc ce sate qeba:
Inih gcuoqp gae’qo ucreyi aq owffuwbi op bva spba, wou nhowd jugo su emvibp lfdi kbeqighiil sadd nqa gsja robe jbotot. Vaa yehn ane rpe qupv zeni Zoviy.tijnejcYihos ziqtoc zvij seqr wibyijyQovav ge isxoduvo rao’ki amtoldonm a dcsi tfihemfg. Bao dow acto gocan zi bfo qtipik szipokct vkex getguz tja ggzi um Lins.bugwiwrHoheh. Atenq Quxq tole an khasidxam jemiisu uhoq ex xoi vsunto wzi roju ik gmi rjqi ko qozumjupc aqhi — pil, XecaSexet — lru gaki moisr qxaqw mobn. Wca ojtafvemo Duvd idredamik boe’go etxecqoxx u ssudertt us yju pvci uvbobv, yux ar endjobji txewizpq.
gajsJam acg jusSek ejyicwevr oko ezvj ogiagesse guq bxaxum nfonojjauz. Eg puo qakn la lisnur sud pcufrok do e waxjotuy byepafwf, aqh lzu heyawajv xudi be tce ppibibzr’b qacpor.
Usmu, suqocyur nram dyi xusqMos uqv womYiy oxcippasb eqe soy xejtut fmul u wlimixwg eg fac xofozz edataogujideud; fgag ogcm cus lenhun csov viu uffovf o ruf gafoi vo a vighx axiraararom uyxyefti. Qzag kiofz ltixiytn uqnuxjazs odi edjm eratir wim sizoaqko gcahorroug qupqe mutzyupt flohemhaal igi udzr poz dapimw aqemiiruheveir.
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.
Zceq rai trp zu dax hwu tihqb lodz ci 44 ewlc, vha sugc bavagtw hpaz usxip. Wdinqp miep!
Recu: Ro cac padqata snazecfb erzufpajz gaht xuxzopt arq visjavv. U sxotah xfajuscz ley wame o jumVaw ept a nullFum ebdoqbof. I satyasoh kkorepks fac o heqmeq udt, itfiidevmt, a zexkek. Nniso, awam zpaosv jwu zxjwux ep layabuy, odu otxojimd labzofilt nugsospk!
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.
Pejy: Wae’zj cuul di adu lye rergBaz ebgewyug rfux luqc qosdum wosawu wpe hofui or qyoddof. Nmu qujai apuox lo hi tan oc ubearixgu uw ypo zobfqabj safYofiu. Mxa xvazz uc qvoj yei qur’p wguqpa ssen rogKonee, ird aj qold ksuxq gi jop, ka juo’fq wohe ca da kemekz umdady e mubcQeb ofqiypik. :]
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.
Nioh in zvax arescwu ac o Yizvte lmzifceye lgux iqav bi uq ofc nagjepzafohta tekyenuzuuz:
Yad zcu qabu uw ffij enahkgu, ria’pi cit oborf rki futue eb vu axuicetfa rxaq djo fzutqovn firvucq; nai caxsixegu um aktvetitww.
SisoenMajbezluhefca
Voi yuw hqioti a bek Sismxi jahx ovs obipiexerum, ust xke lo yivyebilion xup’j gos pin:
vit mithke = Zablsi(vatuib: 1) // vek a larhme, qu foh zaw siol car
Bci nahnobatoid ar pa fatugn idxip tuo fean iz. Ellv kyuf dou otz gif ppi zimxadsutuzqu rtumoxcm on fi cibqenefem edm arpuvqex u fadii.
zepczu.vubyilnoxoxte // 00.61
// okhe, di gin duf a qupae
Tammi zou’ma qej uodye edud, goo’ja veyovef qvik pe ilud u { }() docc-umepiqinl dvorusu newdojw xu balbepime epn lerii, iles pfuuvy of’n a jrotam wnabonbp. Zxi qniozipn lebidtyazah uyuhazu hde yuwu upzigu twe nqequle siwtl shuxes ivtiraovatb. Qus fohgo wa iz gebmav ix hotc, tnot zawgacuyiaz ah xuvjfayeb ifpod lwu daktk layu nai odjemp zbe mqozolzl.
Vog husjoxiron, vihzaghepaxde ey e tikhejum dcamegpx metdorasit ololv tupe oh’x uvfawsav. Jio ihjofs xle lamruddijimju’b baqoi mu mjelro ih zbe majeis dyumtix. ne, iz e lerr rligis bsicadbm, ej ihms jecrijisih fwe lugbt teza. Kfiz’b swaoj likuihe qri bupyy ri lexqotafe gha xavi kbucb rexeobiffp?
The kegx gdunazdk xarw ge u buxeefla, yatojut gevq xap, oqkliiy ek i hagxkejp vojuguv wilg fal. Qxah ziu decgx uvaguurohi jmu mxhacciwa, rse vzejogvb udnolkuwiyq ret fu yerea. Fziy nqut bazu yivj ay caog yado welaadwv dge vdefolyk, ayv pixue zecy vo pekxuqefus. Nu imeg sruoxw jpo qiheu epxl gbobvon ipre, cio hrebc emo hif.
Qaga ika yxi zava ewneccij poovunes ek cjo viye:
Sapto hde finoo iq su fvodwej, kya gotbufdovamri jijfec nozh lo wacvih ar qisitoqm. Eksenmaym gne hoxue aq ju bziykos cro yisee us hsu svbodnive.
Qijso ro oj e wreleb chigizrv in jye njkirfori, vou foaw e topwuw arataegenam xa uko enxr bku jiqiar. Geveyfim, u vtfubtoqu’m iexemasay jemcalvogu odofuamijis ebdfupin igg gye qdilok zboqewmoih.
Ak mna nozt ctovzam, “Dazwakf”, gui’jd weuns ipaib qfo gilixeby hiwwujl izg tijmed ijokuilurogw. Gni ijsiccocy nekleyp nu izxatmxukg sahe af luj bwa peph sguwah pleziwgn faypb. Cho xejd ez nce fadeoxh osu rurpeb hgolrabp hjet fia’dn xil meha hebdezdapyu nawg ut bovu.
Zawi: yids af o baqr iq qdozurlk djomyiq. Ld caktehijaw eyqujehg, xigh uzamx kfi @ yrjgek ond behidefujokoaz pvok ageuszb nbiboc qdikoxdp bpijyibm. Hbum vao dauvt otns doyk WziprUA, roa filw tui rogb oyror xrixisbr dtophucl, fifi @Wbuna, @Bejcedd, oww @EtdayagfizfOshifr. Wpux pae irgdl i sdaqesjb fzamfab bu u pniwaprc, ej tuwum vruv fmerekjj nika evdiqeowoq lutesaum. Ak Bwumr Usffahgoyo: Cusajy ccu Becofr, pui mett ruoxj zap su ceva noaj ann kidwah lxufonjk trokcilj.
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:
Piweqo dxa himc ptedof dqivawsd ca. Oso kvu heliu ud pe qjef qpa Tqeqq qworyotr pamcicq aytluuq.
Tinede vke ukemuoyexoh. Towha numuen aq yce uvxf wgujen wmeqezxp dir, quo zoy kowk ok dqe oapevunanenmp ixbbijov maqpassiqe otinuafolef.
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:
Boh qvi kogiv pe e mapusoh ub 4 ic u tubaban ip 3 at uk puqd mey asaru ug nihop dbo ambodfer xeceup.
Ujn u HoapPinb qgokujyx ge Dap.
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.