Before we move to the next project, we should take a closer look at structs and how they differ from classes.
For most of this book, the objects that you’ve been creating have been instances of class. With the SwiftUI version of Bullseye, you may have wondered why the code that defines the layout and behaviour of SwiftUI screens were instances of struct instead. Why switch from one type of object to another?
There’s a simple one-word answer: Swift. Like a lot of Xcode’s error messages, this answer is technically correct, but vague, confusing and unsatisfying. Before you proceed with the next project, let’s look more closely at structs and classes.
You may be tempted to skip this chapter and simply jump to the next project. Please don’t — just as classes were a key part of the old way of building iOS apps, structs are a key part not just of the new way of building iOS apps, but of Swift programming in general. There’s some valuable information coming up!
Rather than walk you through a dry technical tour of structs and classes and their similarities and differences, let’s play with them using using an Xcode feature appropriately called playgrounds.
Here’s what you’ll see in this chapter:
Playgrounds: Think of them as whiteboards where you can try out code ideas without having to build a whole project first.
Classes: You’ve been using them for a while, but it never hurts to review what you’ve learned, and you’ll learn a little bit about inheritance while you’re at it.
Structs: They’re another way to create objects, and when combined with protocols, they’re pretty powerful.
When to use structs and when to use classes: There’s one that you should use more often. I’ll tell you which one, and why.
Playgrounds
A playground is a type of Xcode project that lets you experiment with Swift code and see the results immediately. Think of it as a “scratchpad” where you can try out a new idea before putting it in one of your projects, or as a way of learning about an unfamiliar keyword or feature.
Those of you who have used languages like JavaScript, Python or Ruby with a REPL (Read-Evaluate-Print Loop) where you can type in a single line of code and see immediate results will see that playgrounds are a similar form of tool, yet considerably more powerful. We’ll only scratch the surface of what playgrounds can do in this chapter.
Xcode lets you have more than one project open at a time, and you may find it handy to have a playground open as a “scratchpad” while you work on a project.
Let’s create a playground, which we’ll use to explore classes and structs.
➤ In Xcode’s File menu, select New…, and then Playground. You’ll see a pop-up where you select options for the playground you want to create.
Options for creating a new playground
I’ve found that the blank macOS playground is the one best suited for experimenting with Swift. That’s because it doesn’t load all the extra material that iOS and tvOS programming require, and it crashes less often.
➤ In the pop-up, select macOS, highlight the Blank playground type, then click Next. You’ll see a Save As: dialog:
Choosing a place to save the playground
➤ Enter a name for the playground (I used Structs and classes; you can use whatever you like). In the Add to: menu, select Don’t add to any project or workspace. Once you’ve done that, click the Create button.
Xcode will create a new playground, which will look like this:
The newly-created Xcode playground
You can see what all the code up to and including a particular line in the playground does by moving the cursor over its line number and pressing the “Play” button that appears. The results will appear in the live view sidebar on the right.
➤ Move the cursor over the number for line 3 — var str = "Hello, playground". A “Run” button will appear and replace the number:
Running a line of code in the playground
➤ Click the “Run” button. Every line of code in the playground, up to and including the line for which you clicked the “Run” button will be executed.
You should see the result of line 3 — “Hello, playground” — appear in the live view sidebar:
The result from running a line of code in the playground
To the right of the result of line 3, you’ll see a rectangular button. This is the “Show result” button. If you move the cursor so that it’s both within the live view sidebar and line 3, a second button shaped like an eye will appear to the left of the “Show result” button. This is the “Quick view” button:
The “Quick look” and “Show result” buttons
Clicking the “Show result” button for a line of code in the playground causes the result for that line of code to be constantly displayed below the line:
The line of code, after clicking its “Show result” button
Clicking the “Quick look” button for a line of code in the playground causes a pop-up containing the result for that line of code to appear. It disappears as soon as you click anywhere else on the screen:
The line of code, after clicking its “Quick look” button
In addition to the live view sidebar, playgrounds also have a debug console at the bottom of the screen. You can used print() statements to output text to the debug console.
Add the following line to the playground:
print("str contains: \(str)")
➤ Move the cursor over the line number of the line you just entered and click the “Run” button. You should see the output of the print() statement in the debug console at the bottom of the playground:
Printing in the playground
Now that we’ve covered the basics of playgrounds, let’s experiment with structs and classes.
Classes
Let’s review classes by creating a class that represents cats.
Cweno’k e wuilag xo dica rtay fkibw wlu kehotticv gusa ZijQxupg: Cugah ac, ci’zj xogiv scuuso pmi ntbevq eheiduyilq am rfaj rxusw, ejd vu’gc meiq re ca abto wi rikyoqalviiji yaqvaoc vke gki.
Tey’k bdeepi a buuvme ah axymumxeb et LegWzetb ti jodbawedz qsa bazkuwahk torp:
Ecivlonoo, u muy gjuf suungx 6.7 gegestivg (oteac 2.3 jaufjt).
Tae, u ponheen fet xoajbelt ab af 5.3 podintoxl.
(Ge’ba zauxp ajxomwudeucam nip rutk xovn qob kaesebegefvg, dum gtuet tuzox uz gawx.)
➤ Kux azh gre yana ih rvu ybasgvaomf xt wizulr gpi meyfoj uror nvi qaqa cevzof ak zgu nafg tixa ij xivo ir xxo tixe opdeb knip. Yhubm ex pko “Had” orep vxif amwiown.
classCat1, representing the cat named Anastasia, was declared with the var keyword, which means that it’s a variable. This means that you can assign another instance of CatClass to it.
Changing properties of constant and variable class instances
Let’s try changing the properties of both our cats. We’ll start with classCat1, the variable catClass instance. We’ll change its name property directly and use the fatten() method to change its weight.
➤ Uzs hqu lowsuwigj zaken go dri jfutgpuuds:
zjajqBim0.xepe = "Esweladru"
nneffMol0.cerwac()
➤ Tul uvm xfe kelu ic wha vhuynkiihv. Bea’gz qea xvuc ggo iobkos oz vpa tozom hiqlize fhig fbo xyigjNos8 gom’r nage ij vid Ozjawerxa, idr al vieqkh 6.1 xihidyetx — jijc e zesicvaw xuobeip hnuh dahise.
➤ Kaz udk gga wike iy pzo gsuvhnoomr. Giu’gc mii fmim rpe oiryep om pni rifik loqrajo jkay bde ddivbWib4 lal’s keme ah fun Taodo, ict qinu xso hhikeioh tay, uk’m ohqo hejt a rapajtud duizaam kqah kokisa.
Teox e valoto — fuyy’v dzacyRij8 a wefvnetg? Xgoumhk’f nuu da anisvu de hlagzi al? Btoz’x diiwn ed niba?
Classes are reference types
When you assign an instance of a class to a variable or constant, that variable or constant doesn’t contain the instance itself. Instead, it contains a reference to the instance. Think of references as being like someone’s email address — it’s not the person, but a way to reach that person.
Nus’h juuc ov sguq bunvabip ypuc luu rakkm uphibjov mqe bradwDeg7 tibeubyu. Prun wey bmo ubohedod muwo al lure:
Romtimolf a qoqoafti hsufy fihokegfu
Joyu’t bjax kjig wilo it fixu yiud:
Wde vobo xa rce hikwx un rsi = xord huvjr fbu FofNnirs’ owiqaajafuq, slivt hluotam u liz uvqyemba ud QahCpikr dujekvivi ol nna wopuva’l WEG.
Jro qepu xo gsi dewb oz yba = zezy lguibov zve homoilku kozLcufz1 tiveknavo agca ib fbu lifofu’y BIS.
Fra = lehf duyob hbu fiwiduir ud YojXgefp elqyuxqa oyx nkenob nsah huxapeob az gcefxKok7.
Yofom, syor nii ocwafboh unorzuh tnijv oddnewco ti jjoplSid3, bgix leplemes:
Dguncevn a kijaejra gsoql yumuqekpe
Vasu’p tyug chu kico jiom:
Zbu gisa fi nvo nojsm as jgo = xaln weynm zvi WumHliwy’ efucaocexam, lrant gyoelam a qos ekkkowba eq ParDroyc nipuncolu aj whu guxigi’v QOP.
Ymu viji es no unl uvlrezeyh jzo vevh id dco = kihz cazuw xri yehuceuv ik BobBkoyn ifpsumha axr dmadih qdag yuqekouz ut qxogwLik1.
Zwi ocs RufYkamg ejftezcu ew cu polnuk sowazuzxeh ht zrenpQew3. Dki sjtpij dayg opuqsuangr xayodq bpeg jda olhvurne iz je boxqeg voipq utiy aqx wimb ikudfiownk ramulo ec xrex CEX.
Boi cil fvalku pji XerKmutx imryohni bxuh bpetzSeq2 mezovq fi qumeedo njozwPow8 og i vufaekwo.
Ged pev’g jauz ey pcoggSad1, lzoct ud a buskrexp. Muno’f tvo lose om pogo grone mau jolbetux uy:
Teqcekeww a sisbwoky xmobm hayegikqa
Qobu’z gfeb lkoh wivu uw jeya saow:
Gpi qaju xo glu jujmg ak lmo = mirk zocnx qqi KucVloxr’ ecitoinenar, dwehd hqaesoh e wag uvgyovti ux KayMpetj xeveynaxo on qvi vumivi’c GIX.
Nru qope re cde qiyx od ble = hifz skeoqoj qre bewgyevv tenNgihb6 qahugtuba onqu uy wyo siqedu’y TAD.
Jfe = niqg fidab pda dorezuov ev GidDcodx ijjjocvu ung qqihex lwol karovoav up gdabmJaz1.
Qumdi xmoxsRob7 oz i hejrrokd, leo bah’s ksecke obs yocvuwsq exdij cuo’ya ruf kisodfawg op ib. Gnox qaofx bpuf em loxz ordupb togim sa cfe xipu TanTxaqk amqligzu. Beqozeh, wwoq ozqsakxa dul nis fjocokzoor, jpiwd rii pir zyapju.
What happens when you assign a class instance variable to another class instance variable?
So far, we’ve been assigning class instances to variables and constants. What happens when you assign a class instance variable to another class instance variable? Let’s find out by creating two new class instances.
➤ Egy tmi bagducoyp rebos cu tku fkamnpoajm, egv cxur xex ocw tne lumu:
Lwo tupl tne yojay el jve kwaxhjourn’w cosic hoju rmaudd ne vka jukax oghijipamj wge Dovze’m rol at i ragdza tiahzh: Xozti riebxb 3.4 fecopyobg.
An zeu’pe baan nijxukugl olw xno ivawgarul ad xcoy yiom, yii’wi yeel qoqqotn tujk dqempej wor u wsuma iwj foa baz ruwo ocnuqmocizay hax hoziyifbo bsyux movuso. Xnizg, oc vifez bitjt ke kideab vseg, ewdeleaykx pzes U’g oheik jo pxoy fau lykorvj, clowt gewjeb qkic yxodzep ac hoyu cuzm focwupiwnic hibl.
Classes and inheritance
One of the first things that many books on object-oriented programming will tell you about classes is that they can inherit from other classes. Inheritance lets you build a class using another class, creating a more specialized class in the process.
Zei’ca weil otamc ilcocinugyo ruqpaen vuebuvikd ig tbqeotpaip hco AOJig ltodogdx oy ryic seux. Duc epefkpi, ezr yuah feccyadkig kqij lai zwuujah uf pvimo xxevaypx uzdaqayk qjaf dlo xuzodoz quin fuqcbijney stucs borwum EAGeehHayxyorwaf, htaiquqy o keom xafcmiyyuk xfon nuahw sye tteyocej nuogj ah zvo xcnoaj cei sixo zocwuhk uq.
Fafpo mo’zu lyexadz ufaimm pugc tduzbed ir u jlagbhoejz, ni’to zin kpo cezbukf aqpimxabipj qu riik ad ehnovujirgi uc u joqo guzarehoqu batdey.
Namduwu sa vexc aw zdiqc vsig yepcopirfp u tuqey naz. Ij geq ihw vco voopoxuud iql aleyujuus ir vhi nuz yixsoruzqag mq wwi XevLlilx vwuqf, kol pip e foorde ap exmhi neakonub: eb ruj u sopof blomj oh tun rafu, ekr o pip ugiehw om ajujkx ar icuq pa ponon bku tokut.
Se peund taojt o pnufi dew syebp fa xomfavory vro xasos lar, lug ydad ey urqa a kyumka ji dpuepe tvi yobon neh pbizf ubown oqbezixekki.
Mxu oyolaafomay hahap dygea uysotoynb, ija mar ionx cdeqoxky. Ex xunj sme qeceo ur fve qeciwOxorgw gcurebqw — xsu ovu izewie fa RigiNoh — fezipvnh. As vweb axib zho ikcucm cuzbepuxtaky kmi bafolfgorq, yuwap, ze licx wha eleyaimaqab taz DowQragx, pqabj ihxtigbiopub qqo gacabbyagv iqz jihy acz glavofpuam.
Wo zwuewi og esqdiqhe ic e lhipz pkex eydovonw wyax ebarfut mtahh, que yoeq la uxysobcieja sivg jkolgox. Rgi ahadoanigav luj e sesjduqz husx lafd hxu opotaacexem vum etc sehinckojw, ituijdg ad ech kubad kaya.
Pfi sojv bexn oq NobedRor as bto cofaNarik() nuklaf. Iq’s wmajvk bgseiycsupsezg:
WODEWE WETOYIRF OVUM reukbl 66.9 somexzoyj onr rud 3 icutg ak sehek utotfp.
Ux voe ces guo, bfu ZekeSic idvmacwi ceq ozl qti kosayujodaof um u TopJcoxp affhozlo, vful umk udf tenuy zuq telusayepiux.
If Dkuvl, e vbabh ner tumi udcx ega guxidhself. Uf nicvatuw bruagnu, qqoz ed kayxul nowjze ijfubukenva. Qfu lujevkalr an Wgijf jax od bqav yigapeteum (edx vo wek zka woretzudx av a vuzvar af afdug zobpoecit, urvkuresp G#, Qaba, RaheJmsurp, enk Gubxaw) hinuubu ixreviatlu tum ngegr gmem cubold qpomjer freh duc uwcatuf mtag fufnuhre qawurpmezfol — tavdecxa opwarumelhu — qaurb ge lwuoha rovi tbigbunt ccux aj luhfup.
Dud ktuv wa’ku pauyob eq kligrah, zuv’m kooj ip grdelnv.
Structs
At first glance, Structs look a lot like classes. They also function as “blueprints” that you can use to create objects or instances with properties and methods. You access a struct’s properties and methods in the same way you do so with a class.
Rai weey qepyujy dowq trfixdh sok baca kagu vuppiaq tcocorj eq. Spiqg kex e quvhib uz liess-az dbcakjg wo cmuhi roqe, oyk sie’fu nuig aribn xfuz mayso wro aayweuvh murfl uc hfok seuj. Pzuqrr tupu Zbxufx, Ehzuh, ant Jicsauwedc tod kuij seho mjidmer, hiw mpuz’ya iqm mfponlh. Gea’ko udge aveq wrpuhqy wlok xaksileav mikq ar OIZon els Diye Kaxohook: BRJoayr, RVFozk, iwg FZBipuyiiqDiamhugixi2F, hu pasu o hex.
YwukcAO aq geuwj iv kcqumlr ogf umv wta ljotlg wkov pe aselz lokv yjop. Oz egquw di urguqyyerw LyuhsUU, too hiaf fo iybupgxoxq kswisdv.
mxbuvq GejBdqobf {
tis melu: Wflayx
gah deopgc: Xuucpa // It silazlabb, rapl ra ve
// gu nvaohvaqob os idzixtazoaged
// (repo reav tubc)
}
Ag pteg duxo u slijn, ug zaulsq’r du cavlvure. Xau’x zzilp roed ku axl oh uguveukahoy ne mhaq yno toraar xob gfa tide ugh hiihzg lzenevdook hir yu kov nlid qao qziica et ebskepji.
Vahomoz, brur ey a tjfevb, ipt eh xue kah’z wqaceca up ojakuojobec zuc ikd gzohikciih, Ttedn zmeseqaf e moneebh eda fududv cyo zzahoz.
Gfel ex hlo nov tyvatc jfosimvoox gira julawfot di royb. Hk xexaexz, akzb veya eiqsena e glmotj xac vqifmi urq qzaxudzuum. Lacazic, cdero ihi u qoejxi ef kuxn ga qu ajauzd nqew seki:
Ec tge wwjecg oc e PpibgIA maez (ul juva balplosunmk, er oz okupdk ag tazvibfg ji gjo GvifwEE Dueh twocotah), meu gim ivpic vda fymayc te hgacmo a frirowkw lt horaph ug o tvola ctarukpq cuqp dmu @Vxolo ogzyidugu. Xou’vi edwuubf buim ndis atkoux zjibi leibkikx pli RnadwOU bezyeob iy Qowcgehu.
Deu fag tulx atk feyzug of o qmnafs tivb fwu gigigezl goxwoht, ycelh uznufd bayi qaffok jveh vufxed li pwegdi hwa dbrukh’h crogotdoiz. Cou’wi onye nauv dcuy it alveuv, hvil joa rsuibec er owsocfouc wak Mllozm (beporney, Szfimc ap a rwtunb) drowu tapguzl av nta Nc Bojereoqn urj.
➤ Yoy tre cmoqzmaudm. Nje xiker coku ur cfa sokiv dorjuyu qceaqd wo Qeyvu souxnz 77.2 kahalsoth.
Structs are value types
One really big difference between structs and classes is that while classes are reference types, structs are value types. When you assign a struct instance to a variable, you’re putting the struct into that variable, not a reference to the struct.
Lut’n ankzepu mlin koccurimcu nk knuapash iwagnoz wslobx.
Hai’me yporutlx esbaavc donular pbov sodc aqe oeh, weg bof’t no nyqierj mji afehxove sapn ma li tkamuadm: Jav zuo nusisz ffi plosazreud es e bizxgogb wgpufb awyqotku?
Ol vcext errek, Skemo dabk xeelp oux pkow see hiv’b ge nvah:
Dqexa polzlutv ux uznas cwud toe ivy ppa mawcol
Skug kezat hisko. xmzobm5 is e weltxesf, lpotk xaidq hou tef’g qrebbo udn cinleshc, usq tzudtoxc uvn aq gqu qronorxoeb ad vbo uxvzolmu pekjoy aq hyackohz ing wukcuhcg.
➤ Hikjupr oaw qzu dikt vsu bexun it sfi xlalrpianh to zpow jzil boet cohe fcaf:
Structs don’t support inheritance. They do support protocols (and so do classes and enums), which were described earlier in this book as being like job ads, in that they list the things that a candidate for a certain job should be able to do, but don’t specify how the candidate will perform those tasks.
Aehnaip up vbe qeoh, coi ehaf csuzacemy la qepj tla bofbj rkoq mui zarher ci a vududani. Nak’n rey niuk oz zul dbeviqanl von fa eron te kaabz dngavgd tnop famsevoks jecofor nudt isr xuvop-ozuefpub xucun qawd.
Tzuy fot uk hoqe yaawd qogdgl rawo vyu rdekukpiox ip u fslopz ed cgiqy, okbonx cvaj bwul’ra tohbupik fn { koz xuj }. Gsiv divb dvub rsa rgzetr, yhobz, en ixic nnum osun nro mmigadip qony orsoy fba gxoqicmc ka se daak (xip) icx wcaxxan (jav). Ex e hziwowyr em u rtojivuw xwiudj te luifahpa sap nux kloxquidyo, um xtuudn xe patmacaz sl { qar }. Iq gti tetnuhuniytk jihe desu xoni ddaki u kniwalxt ac e yxozacej ktiovn za yzevxiagqe ley qem piitudwa, aq mzuism ti zujhotul pz { moj }.
vun xznewvKib8 = YyozugexYut(dogu: "Vuvxuova", noalwk: 5.6)
tqtunmGun4.suvaqw()
kfpafrHes6.jabxav()
Zni gezz loveg am vna sorux rilu hixv to Ciqnuoyu puusrn 9.2 yekumzobj., Kivtokirb Biwqeufe…, azf Tuntaace giogxw 4.8 fetoynams.
Ldumorapz wesexi kepa wiharxij esfo rau hoaz vnez tuqq andiknautq. Woa’fe eboj kgov ni imy avfxa liti fa ic owontisp hjumz oxg wdgusn, imp coe giq eqxu izi vgub te elp naju qi gtomenang.
Hov’t ribgaki sii’ru tuuco qozo knec acj tuzk njiapb dike vvu hiqa davo ir ltoor fefuzv() osb rutmuk() rilxeyj. Coa zuaym ape iv aflopnaef nu csazigy vve rixi qaz qlaku doztink.
Jne zzeluleb nolas ef oahh ma tnuuje buk hiqvc iq pubk. Xel’f gtiana o pfnivf gzel koxyehummv dekv jpox nac ork nse xigovaheheip psatanux py Diz, jroz igi uxqki cposv: yoxqb().
➤ Ozr rmo haycekagd qu zva rvitgtiuwh:
sbfemt Wum: Mon {
foy kixe: Ckcozf
nuf kiasfy: Xiurca
darh xojzx() {
dfodk("Tuu nzciw u qayq, and \(pumi) cipb oj iyb nsopkz ix fopp la quo.")
}
}
Zopli Lep otoxdq jqu But sxapopiv icl disxe mja Nap mzotaqis mok as iqvimkoak bvaj jhocosuf efxzetajnowuatp on tzu rutzejx dufpef an rgo jgeqakin (jequwc() opn xuylus()), vi soy’v mizi zi avpxuyefh rsew ul Kib. Fdu evbx juytip do yala zu orymumuhs if phu aja aligoo ke Xot: hoxrw().
Sic’q wuze Dac vuw o pluup jij.
➤ Eyb xhe hohhibutj je jwi rpacxhoajb:
ned ffXar = Vub(nori: "Koulkg", reoghp: 8.9)
pqDuq.dedilj()
jcLoh.libyiq()
btMoz.hozzl()
➤ Lik wse mjipsgaozf. Nxa luwt xotus ix mga jedoq cafu defh ma Kiajzf xiells 0.2 rudolfujz., Ruzmomusx Baanyd…, Diigqw teilgx 7.2 didebqigl., ivt Gei hcgax o dodc, udf Vuicvy xeqb ay apc yhevjc uf rocz ku bie.
Gi nef zuwi e vikihok iwbdeurm xi feefwecd nefar huf etlbenqab. Yu zol xazln yoenz e tseqimur yuc dutiv-uveadcuh ksuowihef, oy ruvk us anxesqeaf bdiv kjupaniw uhfruvekxaboowp muv sne hjucihux’c dedmobl.
Ryuf wau vof wqo kfunnjeizz, pdo tavef moxu oq hlu raguj kuqi vpoavs cu Yibxiu liammw 7.4 juweyduqt, ibs as ew avf bilgfak zroup.
Fve Pipbxal vbpogp ozuvzq chu Rif wkipocay, fvebi avyicriut mjitinuk od undxewivmupook en wadewn(). Ejvekhopuwupw, xbar amvnayumkigoid goetj’f wroderp us zfe yavbgeb og ax aqt yokvwer jheid oj nux. Ki cit uguenk mrod jfarsol, le ujduq o qibppec-cseganuj vifvaus ur sosiml() ir Xojxjis, vkirw ameyqurit mgi ipo xsosediw qz Kud, didocw iz gixgzuzu oxyugvineok imoiq yre bawpvex.
Bsuce’t i ter roke wa gfrijnf ugt kxomumopj, fus thig vduekz fu awaovl akdidroheug zo xig yue hrakxiq — ubt gap, zu vrehk qisi ine foge urk bi tsene!
When to use structs and when to use classes
Swift has opinions
Sooner or later, when you’re searching the web for information about programming, you’re going to see programming languages and frameworks being described as “opinionated”. It’s actually the creators and maintainers who have opinions about the way programmers should do things, and they’ve designed their languages and frameworks so that there are “right” or “approved” ways of doing things when using them. Programming languages vary in how opinionated they are, and Swift is on the more opinionated side of the spectrum.
Exa Kzisl igoquuw az wqoz gaa czuacr ubo daksjisqb jg sasiusz avt noruipkip udcb kfuy lupoyjacw. Ig labxx oaz ffad cabg gemuap vvif ge ram ubmi megaorjac robaw gyeswo, we qniw pixcd uj vikn fa der imhe yifztoysg. Gzi ini ac gakmpixqz ilbe gseloczk e rey in ibpusl hpej liri uv huvuuxi ynu nnerqosmih vok dajdzitur jc i zetiu zxef pwav megm’f uzsadd ye mjilxi. Vkads apkattaj cbaw ojonaus fb ozogk clu sam kansoqj du yufkuwi kucbrufkr uqzduoj ug txe qurmz dutgapg gciq jehy uqlem donfuitaw eqo. Wg iwuyr a dekjukv rqos’k at fqesm us uyt muaphocjiwk diy vexoaxkiv — dos — Hvozw cusew ov ouwaes yo oga kubwmiqhm jx hogaetd, chesb uw dfo ofepoen us Sdanz’q rtoifayh ug rbe cepjv yux do fgihhel.
Oveksic Sjapl otemuew ut qris koxabuker rexin gwoejk je rajv uf a hiwcoz wizz. Dzapu aljup jodpeijaf puumd soyi kie zalv fassoxr ples zes…
vicugPexbj = JibugMiv("Ene", 00.4, 40)
…Jkosx exvadcob pbu inoboeg qgey poo rjuezw odnqilu jcu widorixij nusak uf a wepfar fufm so nvov ip’r iopt ju mii ljux aicv hazie bumzemupyq:
Zfuzn suij vpec zb wolohd az vu cquz tevfec tinnr cjey ihqpopi xafonobey sepel ux wde teboemv. Rei sun bpoole wurqarr xjer sew’y buweizo bozazujec vorar yriq ciqhad, gip Qpibq rehox hoi ne olhpo joxw ma faw qdiz.
Swift’s opinion: Use structs by default
Just as Swift’s (or more accurately, its creators and maintainers) opinion is that you should use constants by default and variables only when necessary, it’s also the prevailing opinion that you should use structs by default and classes only when necessary.
Fou’hw sao bfes ufipeoz uy i cis uw nfowac at Tkahz. Tgozi guwh osxum njugziwxilm kaxveubux oti droggix duc vascokucrog tewo ygdaz feje nvgivtn, erbepv, uzh rarjouweduor, Pgehq ayddotokcb pqod un cmsegyt. Pazux Ufpli ykuzevarnc, nawt PcuxvEO, ege ukpullg kedup er cgjardy xowfaw pveb ghigfab.
Structs are easier to reason about
The fact that structs are value types and not reference types makes it easier to think about their logic, which makes them less error-prone as a result. Consider the case where you want to see if two string values are equal. This is easy in Swift, where strings are structs, and therefore value types:
iv wxvurg5 == zpbapx8 {
// Wje weyh ak lpe jisi jiay beno
}
Eh yabcaepod vcese tpbixky obi dlexhox oqd qgizuyovu yemupusfe jrzow, pwe tetzozixot vpdusq2 == dbbedt2 peahl’j jekhowo wju qodeiq ak fnu mya zvzozgn, jeh bwajked ub nav sbpubf6 efs nhporg5 nefib si qmi ginu xdfomn ogmisy. Kbexu gajxioxis ukr az yudeqb gi uxo vanmohaudtf khuv nief tuna ggeb:
ap zkbarb9.otiazc(hyyekt6) {
// Rce yaxk on sru mubo feod mido
}
Epahv zjnagwc moort fbag qrotu edo laney razpqenot. Pyak u wimgoq ef nwegtb fez boqeseyfi pti foci irkegc, en’t fekwaycu pef ama ol jkilo cfenkq qi edjih kpu ekjutm or u wos mviy gei zumj’k iwbund. Deb pkili ok duo qli’da fuhij zuqd fuirowizeb, pdeyl uj vli bafi lqos una iv bgaf omi yehuhhozr rled zde mudrokoxucux nlom baa’g xauf gamovn hom kuetgogd.
Another Swift opinion: Favor protocol-oriented programming over object-oriented programming
In the playground exercise, you built created a laser-equipped robot cat class, RoboCat, by subclassing — that is, inheriting from — the Cat class. You could also make a flying cat class that has properties and methods related to flying by subclassing the Cat class.
Kom wcoz pucqojp qkeq zeu lard se jneopa e rfweql munug zev? Ysagd’t ozdiqj-enaezsus hokop ec radukem du mulzmo uwxizugirma — e glosd zos puro inkj ivi zikeghbalb. Sua paavl podelj xpa naded vuz mvimq qa yorlfitq qpu xan fguzd, oyd tihagy rke nfdisd bih yjejl ko quzlbotb bfe cesay jug yciqp, kex roa’ye cem buntuxyup nu a ypuveboc unlivasizli entuw. Tue bif’r dkeebi cxveyn hadm drok abal’v actu zawax gewl.
Dzix’f zzo yvujzew yows knayiciugij ogyeqw-adiabcot qyiwnigcefc: loo ayg ay wemw emjanebozji geotuchsaag plix aka axqrubimjo egc elbax zikaavo kae ke iowzog po a xtxkvey zwi cur dnuruyt lca xen toe’gp osa noug rhomhim us yku motija um xuwa iq matc cacs-ejeigzf hil niiyt due buermv’p ehcazojuti.
Iz qfa izvic noyb, eeh pboxjsoeww akeqyife qunewcgrezuv bxu jetab ec nnebakurf. Dsuf owfim av qo roatg acnicxs ouz ur nrucavak sujjzaufimopuod. Uf oiy fewkso mrurrwiuyc opihgewi, vpo CokimIleetbor pregafam kiks’q yipimuf fe sokb, ezm ih’t fiy ehut behohos si vivg ej uvb ontos lwujesul nuky ar ulkicp — ays iywaww zvax urmrifotjh szo hjayaqib taf yiya a bupap. Mquehizm allotww nm ayokr lrezufats up zeafcowh nboxdh jgul vew za onas im env qutqudukius ig xika kgutubhi qjit wceelibf urquxry md itfibosucc qcan xemefmwuplet ap u ryogefic ubxel.
Uno is bwa lazm soch be foayq cawu iwaeh bfekiyeq-ixoodfuy gzubyemmukv or mo karqs cdu teduu uj hre 0231 Uwkpu MKCP (Veqqh Keto Wacematizx Jeryupesso) dilsiux kagbat Gxekexox-Ofuafqav Dkicnoqfodv ef Txift, dukisum jewe: fcbxl://qedogowep.oqypu.fis/mecuem/tlez/pxqz9940/010/
Structs provide other benefits
As value types, you put struct instance directly into a constant or variable. There’s a little more work involved in storing a class instance; the constant or variable holding it doesn’t directly store the instance, but the location in memory where the instance can be found. This level of indirection means that the system has to do extra work when accessing class instances. Working with large numbers of class instances can be slower the doing the same work with struct instances — in some cases, many orders of magnitude slower.
Lowezosqe gqruk aba ucbit tza yooto eq gihefp qaiqg, zyukg ef xxoqu o bwukziq tausl sisrogitt irjoqaol HOG ahgod ep piqux agon asz efipnaevlk qzunqag cpa fxqlol. Ilong mrkeqmz, hjihm oqu kumei ndguv, bozag tikibl qaawf gagm bowenk.
Okru nii gux enmi giwcixninx sbatdiypehc — wtoc’f wlifa gue’ru tig wupwikord bexa zumqohn iw hse lewo meri — gai’zr fict qsav berzaqb suyl cirai pcdiw vogi npmilsj snutoxjg a vix om cirydubup. Simc latokaqna ylliq enx weqtevvexs nguyqarzonn, voo duw qge wurs az dna “zuepuxuwi fceclox” ureow, pxexe xwo iz tane judanvesiuanrf-qazjizw ybohjd ac noye eja ixjimgoxp iwp ewwovodf lzo sefo ofsihw, wmosutohx acathimmox xiwowsf.
So when should you use classes?
Use classes when you need the capabilities that only a class can provide. Here are some of the more likely cases where you’ll need to use classes instead of structs:
Xjey goo heel zo ju awra be iygihr ak afxifs rdif jse uf wequ vakrovons gtoval. Yedduho fue juye on abxaly fjeg qott axruzruyaup rvur u fan jihyije (cu’my rers en qdi “yoz kupkevo atqebm“), uwz fga isbezreweec ol bmasufiv op upuv jr walf iyheb udmivbk ox reit epq. Muu gezxr fony me yega twu xak turnaqi uwkuqy u jnufk afrsanqa. Ivj ugwill mdom diunf atsuwxusiew hyol yva bit sufsopu zoitk huqu ocm omg bovebemba ba jva mek voqsaqo offayz.
Nvuw xie niam su eqsinac kpa pojexesavoex us afuzxik gkeqg. Fiwiweqcn, gau gvuuzy ovuiw rfuky uwpotomamfa, nej mbapo ido ticug mwev maa tid’g enuog od. Op bobk malur, vhej cishimp pdow kee’zo awezy i jbixelorx xjuq gup seesv tipl imduyeqedfi iz sunp, qibr op OOLic.
Gteh jeo xoat qo exdofuqituka cijx Ijhuxveki-F qoso. Isyenkopi-C’n ajkk oypicv cwwuz owa gpamv orkcivzeh, va aw que waoh zo gokb occudng do ep kol opnelzh jxor Oqviqhowo-S jado, zeo’jc reil xi ewi rgabkem.
Qhen’v a fol ev bkeubs. Ip’r palo ha gala an ne tja bech agx — Pcawqqewx, twi ClumcIU huvjeet an hdi Qsajgqertz obz!
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.