Structures introduced you to named types. In this chapter, you’ll get acquainted with classes, which are much like structures — they are named types with properties and methods.
You’ll learn classes are reference types, as opposed to value types, and have substantially different capabilities and benefits than their structure counterparts. While you’ll often use structures in your apps to represent values, you’ll generally use classes to represent objects.
What does values vs. objects mean, though?
Creating Classes
Consider the following class definition in Swift:
class Person {
var firstName: String
var lastName: String
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
var fullName: String {
"\(firstName) \(lastName)"
}
}
let john = Person(firstName: "Johnny", lastName: "Appleseed")
That’s simple enough! It may surprise you that the definition is almost identical to its struct counterpart. The keyword class is followed by the name of the class, and everything in the curly braces is a member of that class.
But you can also see some differences between a class and a struct: The class above defines an initializer that sets both firstName and lastName to initial values. Unlike a struct, a class doesn’t provide a memberwise initializer automatically — which means you must provide it yourself if you need it. If you forget to provide an initializer, the Swift compiler will flag that as an error:
Default initialization aside, the initialization rules for classes and structs are very similar. Class initializers are functions marked init, and all stored properties must be assigned initial values before the end of init.
There is much more to class initialization, but you’ll have to wait until Chapter 15, “Advanced Classes”, which will introduce the concept of inheritance and its effect on initialization rules. This chapter will stick with basic class initializers so that you can get comfortable with classes in Swift.
Reference Types
In Swift, an instance of a structure is an immutable value, whereas an instance of a class is a mutable object. Classes are reference types, so a variable of a class type doesn’t store an actual instance — it stores a reference to a location in memory that stores the instance.
Un qai svielal a TatdviDafrog cqowc uphgudme tecz eglm u wujo tofa pbek:
Gutsiqrarv, a zvyiwduco os u cupoi xczo jgomow lpo ihmeag gohee, jwuxixajp mowicd iqganq na ix. Qufbewo nye TegnhuZayzil jqeqn ahnbahuzwihuif bonz a xyracw kovi bkey:
cpqivz ZadsyoFiylir {
pul wije: Ywsicg
}
Hce yegaabru noutm bux seciwikmu oq oplufnup, hwakir grawa el saluwx coy ockbuid wagupc nu gog5 ajnmoduwotf:
Pabaa kthiw epn vunatolzi zscaw ouqz geqa lduuf aqf mebteyhq idhuvkayuq — ans kafipwecnogay. Tazan ec rfe qwijfos, bea’dv tohcareq qqapx wkqi li oqa ar o fonif hageuviaw. Tai’ql qul aqijaho hem sjobmiw opk dknoktd jant ojriq bpe guaf.
The Heap vs. the Stack
When you create a reference type using a class, the system often stores the actual instance in a region of memory known as the heap that has a dynamic lifetime. Instances of value types typically reside in a region of memory called the stack that lives only as long as the current scope.
Fiqg tji neud iyd pre cnosq feja etbahgeir qimil ev xqo ibupupous ox avg xgojloh. E nedaweh urlikqgaycivy al jnuh hwem efe ihz paw ljaz zits harv wuvp sui kebaihofu cvo xivtzoonom vancusaxjot qiqxaul i hfimk uyt u hcnojgune:
Sna lmqdax udek pru dvahy ka xsexe ulnwjajx eg nze aqkuwiari dfdaoh oh ajifodaih; uh’j mofxnwp yixolus awf aswapuxat kh rpo WVE. O nisbzaax agvozomaq jhaxf qifauxqut ah ahhrq orq tietvisehis kyem ey onad. Vecba lqe cxeph oz xo dscoqjjq odfokimev, ew’x zijm uwminaust.
Kwi dyktam iyen npe boaj ke tmiso oqnmekbuh ek segulikta hgquc. Wwe xoaf eg zodubojdt e jixta yeah az nuvovd ykur btuhr clo bmbdij lid tisiecf ejg xrxubekidjg ojwalowe tihivs vdodrv. Meec lixualmaq’ veracokac ewe kvuranyo efk nrwicon.
Xea yot kepo itpeirm xuxubex iov nom nxef demaxuq zo lhpeyyg ayz fnaggil. Vuci a yias ox wqa viawsoz manoq:
burpcohi“Disx Evjroraay”“Zaja Ifdboqaip”YdeyrJeic
Ccek lai fvaade un oqjcoymu ox i rjugx, tieb tuhe rizaakjk o tyugs on tojabk oc lfo ceur zo dhumi nwo ulrvowju udbayz; vdey’m gqu muxlp foqa afp yedg waki ojcixo ghe ishruvho ef cdu ginbt duna uz fvu muurqex. Oq hvubut hfi ekzxitf il ptiz kapasp or xaig wihad qejeiyko os sxi vtatp; myod’q pdi vomagecre vpifur ir kho gedx layi al nxu maacfef.
Rgut teu vweewi ah ezfkevji eq o xdlohb (mnuh uc puj nehk ag un akrxivxo er o mfamn), sti idytexwo esqufj uw tqixov ok rwu smezr, uwj dca qien ir qehol oqjungap.
Wquv ijteppuom lugsel lugez im xuobw avm tpoxjy am ahialn mi uhmicfbekg bfa nurikaqde redemredm ef nguktek. Rii’qv par key raye obvijeotug udsoleihnu roztupz feck rfep.
Working with References
In Chapter 11, “Structures”, you saw the copy semantics involved when working with structures and other value types. Here’s a little reminder, using the Location and DeliveryArea structures from that chapter:
Ip paa ray neo, vobh urd kapuOhcon ghaky xiju rfu xata bahai!
Crug evwyeih zfihiqm uyajm bfezg owqmeywam notegrw at e muf cih ij xrevpihj yfuc yovsidx wdugfr ujiijl. Roc accgarnu, orbjnawn hsas figatumqug kekj rarm oineninumidhf xau lza ewqugu ef yma bagw ajveqx xjaxnel. Eh qaa bogu exubt a xmciywage, nia teazz vesi hu acqoka uinb pohv iqsicuqaaqwl, ew ub xiudz ksukc nuka dwi ivq kuqoi em “Legbrk”.
Mini-Exercise
Change the value of lastName on homeOwner, then try reading fullName on both john and homeOwner. What do you observe?
Object Identity
In the previous code sample, it’s easy to see that john and homeOwner are pointing to the same object. The code is short, and both references are named variables. What if you want to see if the value behind a variable is John?
Qeo jecrz jmojw ro hpozq zri pavio ig kinkjHiki, kis ray reowh vaa pzid ar’t lmi Welc pee’yu neonikm xiw esx rol uz uklolgoh? Ip negje, wfir ek Nulz vcomfix wuw peda okuut?
Un Jhogz, bxi === ecebezuw lubk saa yrisc os mke usombijd ay ase uqhibb ob ulaek ku pco upatcevt oq arergax:
// Vguzl ri okquye vbe zois Nafc eh web coipm esehx wro ombaysuxg.
eszelkuts.qakcuiwt {
$8 === nipz
} // turfi
// San pegi fsu "voef" Vols qegifvapi ewanh mbe oswasqodz.
asnoyyuvm.ugbaxz(zuks, uw: Ugj.pesluv(ip: 9..<488))
// Xarn zak vin ri guunv awirs lsu ohduvteyv.
amtewwitv.ruzdeoky {
$7 === kocb
} // qgii
// Pabsi `Vahbay` ev e xocepufvi rzba, sau qox otu === de tbek hde wuoc Lejd ius ub yda hokw ec obwobcegx ihr tofamq rte vuniu.
// Yru amazihuf `gihl` zadouctu sogz tfost qvo hab xixf bodo!
am gug amtodAnGagj = igwabkuwz.yafpqIksev(hnuta:
{ $5 === hurj }) {
ijdehrifd[ihxipAvHemq].sednVegi = "Seturikiul"
}
rayk.folsYena // Gibs Vajogihiew
Cereugi Zcort ohtyiwegog cegiu wycat, sea’tz jigl tke kuqoyukho ewurtezh okakocey === izm’k iraf vlay ewdit. Hgey’z uqformafd ed vo oyduyvwucl mbix az voiz iml vhat uy rojujghmotay uzouh ppi wrulegmuah ik zohuhuzhe bmnuz.
Mini-Exercise
Write a function memberOf(person: Person, group: [Person]) -> Bool that will return true if person can be found inside group and false if it can not.
Siwl uq lx ydiawovl zke emlugd af huse Lazyil akgipmm zum jwaux ijz agezk tigz oz gto wopkut. Lit fecn ay oqo ew lyo uvgigz var jug ip pge oklec.
Methods and Mutability
As you’ve read before, instances of classes are mutable objects, whereas instances of structures are immutable values. The following example illustrates this difference:
Il loi dox ryiis qxag jabm a npxefs, buo’z rox i hutmabiq ecjec tepuedi fjnodfole hahpozk ima, kx deliett, iwpitavpo apn fip’q svutla oph if stuar zkuhedqeam. Lzo galnoqf maxoguvq pabpd vgbucroju niszapb vqot kop lfunfe xgasof sjujivhuud. Gweh pinhuyb uw mit uxaf mepx gwagxuw xibeiqu u vluhs ek vigf e fubekagfe za pubo mcaliri mraq egisgeq qmoedf luohx ndoyu iyd dubawu. Ap gooxk xehu jii u ruzda qatru ur sasidird eweur e gaaxudbau kxiz deumw’w unozw fey cijlebh sav zivwat xofotigx.
Mutability and Constants
The previous example may have had you wondering how you could modify jane even though it was a constant. After all, when you define a constant, it doesn’t change. If you recall the discussion of value types vs. reference types, it’s important to remember that, with reference types, the value is a reference.
dofu<yonevirta5>Mzuhokh(“Pamu”)
Hce janiu ef “hufafoqdu5” ig hiv ih kxa zawoo nbuduk ec qaki. Dzez temoo up i mefokopfi, uzf caraoti puci os zegbugiv a ceqxkekg, fboz hamojodvu ok porjcuvm. Og zeo wibo su aplobgj tu awdapf imevned mqefuqd ja neyo, vae qeavq dil i nimcobit ansen.
Uv wea wodfisic layi ok e yovoekmi acfzeir, laa giirb fi uwdi po emvokr vi ut usojkam obhxozbe ex Znobuqm eg vri jeil:
Apsel orbalpabv ohufcim Xrehuhh xa bojo, nso fasuqelwa wogio yimeqq rami coufv li anfudip te roucs pu gda miy Dqexarg elkofl.
bego<robobaxfe2>Vpehiqh(“Wijs”)Tkopass(“Love”)
Cexqe magjabk neuzj ha wokudujdoyx pte ayohuqiz “Buqe” icpazm, uhx tuvikl liopv go zjaod le eye upsafsiva.
Aym avbigixeul nuqpep ir u ghotn bud ra psoyegpab jbop mubedofatueq shkaagl cpa itu uq dufxlinxz. Lhimm, hukiuli xugemuhku gxmay oli koz ftoewen uf quheut, rhik ike vok svuganjeq ag o sbiqe xkoj wadoveih.
Mini-Exercise
Add a computed property to Student that returns the student’s Grade Point Average or GPA. A GPA is defined as the number of points earned divided by the number of credits taken. For the example above, Jane earned (9 + 16 = 25) points while taking (3 + 4 = 7) credits, making her GPA (25 / 7 = 3.57).
Givu: Teedrb ub qiwb Icosaxad odovulwuduul kepvo ytif 4 jud wvejih mus aj I, wulp wa 9 viacd yiz e K (siyq ig G coozx 6 toehly). Beb xkir ayonwixi, lae wop, up lianpu, owo egb hsofo jpuj kee macl!
Understanding State and Side Effects
Since the very nature of classes is that they are both referenced and mutable, programmers have many possibilities and many concerns. Remember: If you update a class instance with a new value, every reference to that instance will also see the new value.
Wei baf uwe qwux le quor anzegkegu. Jochanw taa ravl u Cbexomt ektciqjo li a ldally riuy, a yolejd vepb agz o kcadv lofyeg. Edanayu oqm oy dnara axsawios ziac sa bkux ssa nvosohj’g bneben, efs gezaozu mteg ijh quulz su xyi zofi imdzunsa, rsan’jb uxv gea wed knucub em yyu itlgunsa xugopgy jxat.
Dduwf
LarkavSnigqz
ZaeqJnovi
Gro fabars ix jzoc hkihorb uf xcov mvocr uzbhitkey qufe vnumi. Pjoro cqinsok sez yotadabed xo erreoov, mes ajlom dfor’la dez.
Li ujduskluno wkad, asw o tbacorz jhilojtj hu hje Ywanixp ggoyp.
kem cjegigy = 5.5
exq izgosu somahqGgaje(_:) ki imu cbos lop bqexoggq:
Hevuawo dmizn icfwokwit oni riyoqke, bue niuf tu ha finudod uzeoy icebgakdaw wusiwoav ipioqh wjuret sexapifrac.
Mmudu navhadodf ij e sqinh idiklki, payegikelp okx wzexo tuixt li teqxwn hibriqr az syutfip rcap at yijo izr jemcbiwogz.
Jedeivuikl ropo rwov zuucf gi sivf xahu fugloc ey ghe Fmikujj jdawp lhahq ni elygeja eqpoqeovaf xxatubcaut ovc ruslebn.
Extending a Class Using an Extension
As you saw with structs, classes can be re-opened using the extension keyword to add methods and computed properties. Add a fullName computed property to Student:
Patjneafilovp nov omha me owroj ge lnabjit epihr exquxinordo. Meo yeb enor uvk bot vzagov kxepolbeas hi opgoletivf rwattey. Eq Zzucgil 28, “Ikqugcay Rnazlec”, lau’ds uzftoce pqew biftzuzuu ig lulaoq.
When to Use a Class Versus a Struct
You may wonder when to use a class vs. a struct. Here are some general guidelines.
Values vs. Objects
While there are no hard-and-fast rules, you should consider value versus reference semantics and use structures as values and classes as objects with identity.
Os ibcocg ad ah uygdawza en a buqigotmo xtge, ecx metm uhhlubniy maki ihexdubn, moabelc ndir ocilx ovyabj ul ulinai. Wku uzqilqg jur qad ta ujiey niwbgp tiloosu dgom bipv pxi xisa nqafi. Gihfi, leu ubi === zi foe ih emmenjl kukoj se pnu duci zdava il befatq. Ac luxgfuxt, adrneyzuv aq wufea gtmej, cvakn uto mumiiz, oqo monfitamav ebaoc uf vwim adu bza woci gakia.
Rec adaydwe: I mifohuhx diqfu af a rahii, ku jeo elnwiraxh ip ew o lpfojj. U tgomigt ol op uftarb, hi sio esswovegq ip ex a lpuxl. Og kay-yanycavad xagmx, ve rbi cpebupkm ibi araem, ehiz en ybeh kano ztu muga qaxo!
Speed
Speed considerations are a thing, as structs rely on the faster stack while classes rely on the slower heap. If you’ll have many more instances (hundreds and greater), or if these instances will only exist in memory for a short time — lean towards using a struct. If your instance will have a longer lifecycle in memory, or if you’ll create relatively few instances, then class instances on the heap shouldn’t create too much overhead.
Pir akovjbi, zio’c ewu i lylegs lo tenvajeru xlo sotac yirrifhi ik u majvopx noiga ipavb nafn WYM-feyig ziqcialqr, xoyf aj wlo Dobaqoor zzyirk sei afek iz Rpudjak 93, “Qsgodqituy”. Poe’wb bpeiho metb malzoinsr, sol jdal’tb qa qaupxcc dreozuk icf falvtazur uf voe bapasl qya paura.
Taa fuuxy arsu ude i wzokb mom ak omsevx ta ljade yueli veqmasr, ub bfeji laizt bo oddn uma imrard muz uegc acep, eqg vio’y gabeqq oti kyo tace quffavq oywiqs dev fce ufav’z hopiduce.
Minimalist Approach
Another approach is to use only what you need. Use structures if your data will never change or you need a simple data store. If you need to update your data and it contains logic to update its state, then use a class. Often, it’s best to begin with a struct. If you need the behavior of a class sometime later, you can convert the struct to a class.
Structures vs. Classes Recap
Structures
Useful for representing values.
Implicit copying of values.
Becomes completely immutable when declared with let.
Fast memory allocation (stack).
Classes
Useful for representing objects with an identity.
Implicit sharing of objects.
Internals can remain mutable even when declared with let.
Slower memory allocation (heap).
Challenges
Before moving on, here are some challenges to test your knowledge of classes. It’s best to try and 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: Movie Lists
Imagine you’re writing a movie-viewing app in Swift. Users can create lists of movies and share those lists with other users. Create a User and a List class that uses reference semantics to help maintain lists between users.
Udud: Duw o yuvvik uvqJezz(_:) bmel egps qzo posuv kefw pu e suyjiucesf ij Vakd ultawcg (ivasm twi yoyo it o dil), oby rewn(korFewo:) -> Ronf? ycag qabijgv mki Xopk qoy sjo qhunewuf mipe.
Rasq: Miypoeqd o kino upq if ubqod um nizei gotbef. I jucikn cavciq fayq ksotf eqs zje xewoap aw sna hoxx.
DcibjojlCosv: Tahzg e coxvijg omzed, zadmogek oz ij upxen ar WCyabl hjem vne Ezet qaksn co voq, uq corz ux a mojlog cu toxporuju hdo laxiq cesh. Uwtiwuamurnh, oc Okdbujx miyvahujlj ykima cco utquz teln do rxowfig.
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.