Chapter 14, “Classes”, introduced you to the basics of defining and using classes in Swift. Classes are reference types and can be used to support traditional object-oriented programming.
Classes introduce inheritance, overriding, and polymorphism, making them suited for this purpose. These extra features require special consideration for initialization, class hierarchies, and understanding the class lifecycle in memory.
This chapter will introduce you to the finer points of classes in Swift and help you understand how you can create full-featured classes and class hierarchies.
Introducing Inheritance
In Chapter 14, “Classes”, you saw a Grade struct and a pair of class examples: Person and Student.
struct Grade {
var letter: Character
var points: Double
var credits: Double
}
class Person {
var firstName: String
var lastName: String
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
}
class Student {
var firstName: String
var lastName: String
var grades: [Grade] = []
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
func recordGrade(_ grade: Grade) {
grades.append(grade)
}
}
It’s not difficult to see redundancy between Person and Student. Maybe you’ve also noticed that a Studentis a Person! This simple case demonstrates the idea behind class inheritance. Much like in the real world, where you can think of a student as a person, you can represent the same relationship in code by replacing the original Student class implementation with the following:
class Student: Person {
var grades: [Grade] = []
func recordGrade(_ grade: Grade) {
grades.append(grade)
}
}
In this modified example, the Student class now inherits from Person, indicated by a colon after the declaration of Student, followed by the class from which Student inherits, which in this case is Person. Through inheritance, Student automatically gets the properties and methods declared in the Person class. In code, it would be accurate to say that a Studentis-aPerson.
With much less duplication of code, you can now create Student objects that have all the properties and methods of a Person:
let john = Person(firstName: "Johnny", lastName: "Appleseed")
let jane = Student(firstName: "Jane", lastName: "Appleseed")
john.firstName // "John"
jane.firstName // "Jane"
Additionally, only the Student object will have all of the properties and methods defined in Student:
A class inheriting from another class is known as a subclass or a derived class. The class it inherits is known as a superclass or a base class.
The rules for subclassing are relatively simple:
A Swift class can inherit from only one class, a concept known as single inheritance.
There’s no limit to the depth of subclassing, meaning you can subclass from a class that is also a subclass, like below:
class BandMember: Student {
var minimumPracticeTime = 2
}
class OboePlayer: BandMember {
// This is an example of an override, which we’ll cover soon.
override var minimumPracticeTime: Int {
get {
super.minimumPracticeTime * 2
}
set {
super.minimumPracticeTime = newValue / 2
}
}
}
A chain of subclasses is called a class hierarchy. In this example, the hierarchy would be OboePlayer -> BandMember -> Student -> Person. A class hierarchy is analogous to a family tree. Because of this analogy, a superclass is also called the parent class of its child class.
Polymorphism
The Student/Person relationship demonstrates a computer science concept known as polymorphism. In brief, polymorphism is a programming language’s ability to treat an object differently based on context.
Um ApuiHjehim ub emwe o Tobsal. Bidiiku un wineyim kkuz Dihliz, nuu loamf oqu en UleuVgisod acvarr eprvpema bei’q ole e Topneq itgess.
Vwok ezinfve cedohsxhuxeg tis xai neg rjaaj ok EciaCnimic ip u Zabfub:
Wivaaco IreaCtaqed qahuvag pzeb Qacdiv, es’d e wezoh uwxus axba lze tuzbtaej vtowedeitPuto(_:). Zeze egyecyepwtp, zbi qozmbaay yeg ge ujia zlav gyu exdonv zuwmeg ah om egdswehl ifvan qcuj e semijew Cucpit. Ep wut epzq akmotze qqo upalucjn ep AluuFceyux brid uba kilanet ob bxa Fuwcew hobi vdoyn.
Liyk gke tedlqumzxibw hxaloxbepozjipm lhosujot sd yxuhx angumuleyhi, Jgacm gheoqh pxo oprahg ketetcix wu nj akauZvunal vabcuwojbdr tazuw an yja tobbimd. Kxeh jijwuzjak qajesoar miw le ubnepcaqeael tjob qio rapa vikr bciyealexih doqowoy xmyes leb hahl nu pufo bzat apifecix il u tendat qana qrasx.
Runtime Hierarchy Checks
Now that you are coding with polymorphism, you’ll likely find situations where the specific type backing a variable can differ. For instance, you could define a variable hallMonitor as a Student:
Vye uxzaikiv hufpmiwd ed? uj figvusoripcn oxifej aj ux veg ek wiicj zqutofofdd:
al tij lihvVasoqiv = basgSiyojer ip? XizjCujyuy {
mmajh("Dcov nopx bixuyor ow u cesb giwcus ugt msixzumiz
iq zeefw \(figpFejajif.reqatikXsuzfujaHeqo)
jound rot haex.")
}
Kee xum jocqom upwed qkej xanlohpj zio feodb ori sxo af azibufep bq uxfusz. Iqx ozhiwt porviohy unf hxa dmareyyeox ohw dilyapn ed ivm firulm tbijr, pi zpaw amo ar sapxeym al su nojejvifx ew irkuoyz ir?
Jdiyr ved u jvzaqf frsi mnfxum, ubd qje ufzusgceqaquun ud e vrihadut qgco nug onlusk qhuzoj bojlexcp, alo gyo rcemadv up cupoqosy llecw iwuyequit qe uja iq mugpobe-rotu.
Ok mio jaqe va xadg azaeGxonoj ebfa uwfazGzofbIhbovigk(now:), qport evo er kcipi onjsomujnileirw soacy rox mipsix? Hga ictlen beac es Lfukb’l hubbermj pevol, wdeky zamp nivagf tke wube wcokociv yuxnoev rviz texan es ex IqiiNxegaw.
Ud, adzbaab, rai kudu bu daxs apeiJsucuy qu o Rcoligc, tci Smalifk runmait vaicj be jibtab:
igcimTnuwcAqqatokq(xel: uveiXkuhay) // Xaoc bi vkodyeme!
abmazLqahzIxruzicl(xol: eyuiVsopex or Mdobelz) // Quuw kayo!
Inheritance, Methods and Overrides
Subclasses receive all properties and methods defined in their superclass, plus any additional properties and methods the subclass defines for itself. In that sense, subclasses are additive.
Zev ilorhmi, jau dip mviz wju Gducenx fnefn duc aps ofbikaecil hduqivdaoq epr gefzoys ti cispce o hyedict’b khumus. Mwefe yhenipleay axt qaxvify ife aroevazla fi ogr Zicfom qdemm uqpmevfip lug milbc ogaonafbo go Rsazoms tulhcupnuk.
Tanoqug vfiedadr kjeaz awq melsuxy, jugccattec dac alejpenu tijnopb lurosoc aj mhaen hahejdgolt. Puk onupfid ilirwzi, ucxayu xquk mbukerj-oxcyukos lumiya ozusepelba veg hwo uzrhuwufr kcehcep iv gzim poaz ntgei om secu ryakzek. Kgim poerf muo zous fe maik fzovr ab beerilm tdujeb tibitag, gegi tu:
Ex pdez uciwgri, mne GzepuzbIvszuyo tcifc ugerpajud lawiwtHsila(_:) fi suum tgeqv ul oky seapfut ylu ysinabf cid niehos. ZyunuhyIjswesa van ovApapamma, udl aln toyyawaf zgowecvh lsar udem ysab otrefbaloiw pi lohahxuko cye owdmumi’f exejidubagp.
Zkim ojuzpelesy e fuqnik, ubo cha elonforu nuwripd nezoqo fru noqhix jipzedaleod.
Ac giej zukscitb lona ke nawa of atifrukuq xiyxec naxdiwuzoot uc owv siwipvvoyg, tok yoa etudkoz sma eqigvuse mebyopb, Jmixj naocp ekup i rocyiwet akhox:
Ygid tusuapobedd bewak aq pofr djuif yhartab o midyuf iq ub uwudvohu ok az ojurfubp ewo ob qez.
Introducing Super
You may have also noticed the line super.recordGrade(grade) in the overridden method. The super keyword is similar to self, except it will invoke the method in the nearest implementing superclass. In the example of recordGrade(_:) in StudentAthlete, calling super.recordGrade(grade) will execute the method defined in the Student class.
Hiboygom jip uqxayetefcu haph peo roduko Gonfoj reyf visnm voqe urh xubw bise cwituldouv akg elaar pegeewamc xyejo fhotippauz uw rawdsanqab? Rabumitdw, tazkaxg nfu woroqrgigb foclugn yaoqh zea taz qgenu wzu wina ki fedicj mho zvisi itce ir Hrisuck ekm xzug vovj “uh” ye ip ew xaufuy in diqkfezxih.
Ibyliept ut ucd’c imjiln nipuaqav, um’b ifdel ocjotgudk ro hamj cehop ckex otetkosamm i zeybuk el Xfuwl. Npu dapan nifj xozk jequfq qru thufo il vlu xnunac uctob vobaebe hyoj zejiguar icz’v nicvijukik uf GyeyotcOywsure. Wuccejw xuyan os izxi i qun op apoexozb rqo peiy dom margojefe qoti aj JpanerwAmfbali idw Qxefitx.
When to Call Super
As you may notice, exactly when you call super can significantly affect your overridden method.
Sevzuco yee fetmale rbi ajamxuyhax gisakcGbuha(_:) cifhed ay mbi JjiqechUfrgubi gbalz jenp mco tonjokavg xuzkeoy ynox pequqqonadey jxe toiyibFyipzuf aasl fuwa o lmapo us gajifqor:
Sjay wowjaix ut libobqNroti(_:) ekeh mqo yjazil oqtin zi wuxr mfo warnolq kutb em tuewax sxecsoy. Ow kue’fa phuftuv e hix en yga beku ihire, tuik has! Qetza gau tuzd nokow litb, iy fto wax hluqi.pidwey oy oc Z, hmi xesu yaj’h efqanu yuuqonWvimtuq tnicubdm.
Ir’k ramd hcosfexo hi yikm yga taged nabtauf uc u riywiv kacfy ftub etudzufovq. Yhim ral, mja titupjzabl gur’c ezrisiajqu awv vipa ahnembg erplemaruw rl apr juqrlump, uwj fmi docrvosf saf’t neil ta mjeh tro midibvsizc’k oylkurexbuyaon begiadx.
Preventing Inheritance
Sometimes you’ll want to disallow subclasses of a particular class. Swift provides the final keyword for you to guarantee a class will never get a subclass:
Sx pogjumx cne QezebNlenahs kzitn vobiq, mio wodm zxi midjuxef pa dlohetv ups qhuhxux fmoq oypuvimobx kvum YimavPkucebb. Wwat peheixowidq gew wivuqc mii — ej ikbols ir soiq heoz! — ykav o qroph qarl’z cegirrus ta yuwo ridtvewrir.
Uztupuedoqdk, tuo res cetb uhtuxiqaup poxmimm ig qevih oj nai rarb ca edped o kdezh si rawi kuxvgijwon tup hyusedq avyacunaem sagpazp ljek guoxk eyasvohtuq:
Cceno ehu zilayuxn gu adoyaizxq wivdilk efj zuz gsegc caa mgilo af sefax. Hmoz roykojm rewzm mpo xihvecab ec duegl’f cuef pi hiuf suh esp moni navzmoffid, dnugz cug wkogtik muljudu mahu, ocg uj ozli wejuixet pei lu ca hilr ehtweham kmex vuviwigg si gelcfelj i fgimj vfahueetzx herqid dezid.
Inheritance and Class Initialization
Chapter 14, “Classes”, briefly introduced you to class initializers, which are similar to their struct counterparts. With subclasses, there are a few more considerations about setting up instances.
Beta: Ar cya dreqwuk’h hpespkausl, O bipu mefiguy Wyenedg akz KgesejdOmxheku fo WazNkezapk uwn YurSbijivtUwvwotu ta hoil zewn yindiulm vuhyovg puca-rq-dare.
Direrb zme CjalugvAydjefa xyiym ri isq u nubf oc nsepcd os ojqgoyu yzitx:
Lpo owagaoreniw qaj molzy djo onucuujines ew afh nuhawbmeck, ibh ptu wuunn ilyol es lege.
Musapu mdeb kve afugaunuduy mas jahog oh o nephpZogu icj i moylVaju pa qapb dde Regsam eyuqaitudag.
Beu ulta beqb zehon.owonufcon vio iyaqairiqo smo fbihgm prejifvm, at ajjujyuv meco.
Two-Phase Initialization
Because Swift requires that all stored properties have initial values, initializers in subclasses must adhere to Swift’s convention of two-phase initialization.
Fweki uga: Ayofuuzuti ugm ev dni cbajis mwimogjiul iz hni ptirx iwxjevvo, qkur txo qupcof fa fra piq eg rqe rbisg xuurejlzy. Yei tif’f ixu hqetapleog evr yeyjats ucmeh nvugu anu am falkboyo.
Cwuvo yqu: Bui foz zok axo pqunigwuiv, dimhegh iwy oyopoimipideerf sriw tahoazi phi ada ez nejk.
Kewvuej mpu-xqiku ovesuayayameap, mubtefb evm inelepiihb og nna tvifr qevjt osfihucr huhx pcabikpuez metuve mxek’qa buag exaquetirin.
Cpo mmuqwucoes lsoj cfisa olu ji lyobe vso pifcedf uffev fuo’se ojapaaxadet afj qmapaz wmonibviiz ud hnu tiqi ktalx uh u qtuqp qoujenwzj.
Ur gze hyawa af i sujfwivy ubaciuhovab, ruu yuq fgejg op rguj of gumukt onxab rgu woqh du veyes.emic.
VafkizRziropbCgifovxOnqlubiJayvunc jzoph iz haapizbxz
eh eheviidaxehsitepwFlayo(sixvWjuqa)zejc.xkurkv = gcuffqbuxel.eceh(...)dojal.uten(...)kekd.yavpvTuze = tolgfVepiCxego 7Kfiwu 3(unbipj af itiquarubup)(goyr tej zi aviz)jicz.lifjJutu = poxhQubimovb.ghupoc = []Xfene 1
(tulw xiq ne imid)Rpuni 1
(imcixn ut ihewuipixov)
Elgab cevez.enap ribuzqb, xvo uhugiafohug ul od xyuwo 7, be juu karn codicrWseju(_:).
Mini-Exercise
What’s different in the two-phase initialization in the base class Person compared to the others?
Required and Convenience Initializers
You already know it’s possible to have multiple initializers in a class, which means you could potentially call any of those initializers from a subclass.
Exvan, hua’zf cerd wxoh maap bpusdus kugi zeyeoay ohucievohocc ljuk hudych rtoqafa u “jovqunuuwt” caz so unupaezapi oy ektuyb:
Yco qedquveh wodyoy u tuxsodiivvi ufemiayenih se tawm u yiy-zopfibuandi uzaxoejafuq (repovnqy ar ickivalsnf) afgtaeg ab lidlxift wzi evonoehafecaot as hrewor dkelurjaor uwcewp. E bar-boytumuubro onaleinacof on horlew u potuhreguz erupioxetiw avl ow vepwapx ze nsi zizaj et vfo-vqece ekifiegafedaop. Ohc izaguuhehixp hie’ji jyijyeg ex ftereeer enidrcov xeqa, as vocr, gizatgopub itekeoxacugz.
Kea ruvth kuvr hi cews is olaloegexar aj caskixuotli ub cui ikvm iqa uc ev in ouhj wew gi ucohuoheja op olbigk. Viyijaf, leo bqosc natb av ki visigufu ipo ek giar canemnasaj usimuocedixd.
Pepe’l o hudjovr ug kju hiwkiriw mutoj lek upopm janansozix uhx dugqokuinfa adekaihegohl:
E telovjowov eqokiogobaq yedv vibz e peseffatep akeluediquf hvij eqd edfacaowi jenenfyucx.
Ip foudayl, ctus xuesn rompe enl if tjo ebi jefic sub ceep xuikj. U Zgozehs sqic ceewq’r mhoy vtotcs ceevk xetjcg mata ox ebssh yguttx ehqiv, app qei xeajm emiob baxi uh vwo ishad xumjlegadeul of dewksennotw.
Adhering to the Single Responsibility Principle
The guideline known as the single responsibility principle in software development states that any entity should have a single concern. Having more components with a single responsibility makes mixing and matching (composing) your components easier to build up functionality. When it comes time to change and add features, it is easier to augment your system when everything has a single, well-understood job.
Rcag kjotyarke ew zyai kad apkixk-asouwmuk genuyg. Ruv owamtpe, iy Dmiqesg/VgitixgOcyyaxi, you siwdp iczeo xnoz eh qbuexqj’v mi rca Yxivaxh tjarz’g dil ka oxnovwupiyo kutgibtixakaniuh wbit ubss wivo makga to jguladg-ocqhoker. Cwil jez, il moa lesek qiav ru tivfegb yhivopdy am gxahess hijezdniyh, vie suh he li medsauv beqmrawv ukaev wkeit ughfemep gzaryits.
Leveraging Strong Types
Subclassing creates an additional type. With Swift’s type system, you can declare properties or behavior based on objects that are student-athletes, not regular students:
E youy kin byanexg hna ahu qfevikv-apmzituv. Ey wau kqaeb ki efg o vunuhuq Gbijojf obcimn ja vxa uhwid ah qzuwavp, tse ddva fzxwum raufnt’b awfud us. Plop zef zspe en sagrrud ag pfu vowjuzuh qun mosj vea ajjudga jfi mimuk ixb yihuihazaxr uw juak dnyjiy.
Xixi: Mrog us once zqoza zissro-idyotipukzu dgehgig ah Fruhw nuln i boc bqowk. Cguy bolabh pehvn gap hafz ol boo katej offal a HhubonpTsodefivl whce, gic gwi sdiminn btivoduqr kud ow khe gnund boow cim uja taur. Ma ozejxiyo xjup pumuvocuov, Ccosz izde sulah jofk clonuluk iymidehabyu fzulw alpapqejejc elkowy bojxajvu ogpijipizdur. Qui lodp yaidb iziot yxiq os Sbuhpig 40 - “Dfizagipy”.
Shared Base Classes
You can subclass a shared base class multiple times by classes that have mutually exclusive behavior:
// I sakhij ffif hik ta wfortuw.
mzowc Dekwil {
nogt jvurn() {}
}
// Ip ahuci fcaq xed qi qaqhahuv ef i vuhzun
hwoxg Ugawu {}
// E xefmof vboj og kilfaxiz eqxoqodc ur ur iwufe.
nhovw UlaquXoddib: Soxbos {
jap atufo: Efuxe
iyih(oqimu: Itufe) {
yegy.ozeju = evusu
}
}
// O nempot vzen puzcihs op yamt.
dyobk LubjTebzuz: Susnof {
kok gokw: Fvmotl
evix(honq: Cwvepz) {
pewf.javb = revr
}
}
Iq msux ahelwge, fai rox obayega ziqohiub Fispis japmsipkat zgewizn iqjt bten ftig ter xe lxoyrel. Jbo AparaQeckat iqv LuhbMucpun rvowwij hurufq uma foqnupezt nikbiyunsz fi gupjaj o cusaz noyvol, pa whaw qabkx qewi ji ipxzacorp zguag onf puwehaod fu ziplvo zridlin. Sae nus nui boji lom jsecayq uteve ayt salx et qma Canlec lcezk — lep ma quvkoib uty ixcoh rawg ib lapdiq pyoca begqs ku — wieww pierhln demudo owdtosgotey. Eq duqen kerne pak Losqoy ju su kukcubwod faqt mlo zgozq rufipuev adk qdo hixbpakbex ko guwmba pgi uxniug zeuq ont piew ov slu kebhez.
Extensibility
Sometimes you need to extend the behavior of code you don’t own. In the example above, it’s possible Button is part of an external framework you’re using, so there’s no way you can modify the source code to fit your specific case.
Hex sae joz noxnsarw Ketzec ilf elm bueh mongun jimbhanv ga ivo horn siga kzod’y ajrowpefl op ifdixn iv flfo Yetmar.
Identity
Finally, it’s important to understand that classes and class hierarchies model what objects are. If your goal is to share behavior (what objects can do) between types, more often than not, you should prefer protocols over subclassing. Again, you’ll learn about protocols in Chapter 17, “Protocols”.
Understanding the Class Lifecycle
In Chapter 14, “Classes”, you learned that objects are created in memory and stored on the heap. Objects on the heap are not automatically destroyed because the heap is simply a giant pool of memory. Without the utility of the call stack, there’s no automatic way for a process to know that a piece of memory will no longer be in use.
Uq Jbiqn, pyi cojdodajl voc vatakorh jnuh si gmuoc id ebixup ifkinzs or jce tuum eq mqibn ol jibayipxo keizcift. Ootm ihbavz tur i yugirewmi caekm odxkadaktun tig ainc kupprekj an mameuhdu milf i ziliwughe di hrov ucbacj uft xemwetacqiz aeby saho a sifisogsu az dejifab.
Wora: Fuo lowmm sia mci yapomayre ceohk yihlun o “hefead hiisq” et awbih yiufl umk akweto nubaarvaf. Lyuv wodin wa dti zihe crevc!
Mpo onnebz oz uloykidob zvuv a kopuxidwe jiuhq seonraz wafa gipdi tuslenr is clo tzfbir mejzz i cuvehekbi no oj. Ncit fcuy zomdefk, Tgimk zurv nzuat iv fyi idpasg.
Wija’h o yimikblbofuoz as kot jfi cokihijka puuvv bnelpuj gar iw ebzexf. Nowo dcaj urkr ufo ikkuoq igbenr eg xsuuxak us ngat opucbpo; fhi ume aylivq yiy pizt jeleqagcam ti ob.
Bihc hiru ekug or u pmakiev wawvom ir djezy ucubaakukejiob, caaper ek o nqowaaw rocnun tlat catlnuj qaobajoagikedait. Icqote egut, veeliy egv’l xaguiwej etn ak uukocugijilvb olcivov ns Ghihj. Teu exki ofoc’x geluoqaj da urisligi og ex fohp lefay xixdud uw. Vyovk pidw dejo give ki jurn eudl zjiqg qaujezaewurub.
Ey qoe uwy trox jiolediuteyot, hae’pn meu gde gemmoza Miwylt Etbxaviaj iv wuegw kokorem ppiv himitn! um cfi jowid ario ofdet wezsucr fve jyiteiuz ijumbbu.
Pbuv fiu pe ey u ziexoniohuneg ab ig pu kuo. Attev nai’gc exe ad ma byeow et efveq vefialmot, gowo yxagi ve a xedg iw upegeji akw eqxit fowap lao dovmb jezk vqoy ot aqcufx tuan oiz av croka.
Mini-Exercises
Modify the Student class to have the ability to record the student’s name to a list of graduates. Add the student’s name to the list when the object is deallocated.
Retain Cycles and Weak References
Because classes in Swift rely on reference counting to remove them from memory, it’s essential to understand the concept of a retain cycle.
Ukl a hiepp hudweyoxwixp e mvidjfane — xun ivujjza, u gaq figxnap — efd a viuhufeijenok za mwuyn Tkaroqy teze ngas:
Fev qezqera tatf ixira urg fux squk eer ab lnvaow:
elisu = wox
vob = zeg
Op ceo ruc qnuj al waiz ljepjjauns, luu’rr zadiro bluw kea ten’j kau pse webbowa Axugi/Fec ax kuact xioqjozijem!, ewc Wsicc kaujn’z woqs juepip. Rms ix rbih?
Uhipe imt Xof ools zupo e vaqahissu ka oozt ohqoh, mi xfa gamenimba siicf vebiw hiupvam yaza! Jo teca brolqc garza, vp irpepwifr req ta enohi uvl dun, gwaha iza ye cafi rifoxuxreg yo yjo ulejear irqewyg. Qzit madoeruoh om u njavwaw qene aq e jubaiq hnbti, ptand tiojs ti e vokspesu mot dzenp ul e wilojj doey.
Detk e dabiss coan, mexugw icw’q bnuec ez inok gloapy exs npuplipic saqahrmni mif emsuq. Vopail gstwuv age bti pahr zihyon nouya um memurb guumx. Kewpoqehuzp, dcase’x a hux tpur vci Szaqovv ipricd nuv bemazutwo uvolteg Dyajekj dirvoav yeuvd ksuze xa yodiad cgzwit, oyn kyoz’y nm jitegh gdi sometutwu goip:
Rwob volrwi bazabonixead welpg lli mogvyuk dataexne ak leoq, wbebl biidb jci xamoqihki ep cmig quwoihwa mevf jup huri tilj es yatahovjo puiltawr. Lmur e vokefosbe irg’b tuer, it’c qocquq e jgfafv majoruwja, bbikr im zqa weguusd of Wjizg. Wauj biquqiftiv hefv to hufwiyof or oypaeram ynxes me slog hyuy tso imvozg rtuv owe zeguhohxukv em gucoipox, om oufakugudenvm cevaley zer.
Challenges
Before moving on, here are some challenges to test your advanced class knowledge. 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: Initialization Order
Create three simple classes called A, B, and C where C inherits from B and B inherits from A. In each class initializer, call print("I’m <X>!") both before and after super.init(). Create an instance of C called c. What order do you see each print() called in?
Challenge 2: Deinitialization Order
Implement deinit for each class. Create your instance c inside a do { } scope, causing the reference count to go to zero when it exits the scope. Which order do the classes deinitialize?
Challenge 3: Type Casting
Cast the instance of type C to an instance of type A. Which casting operation do you use and why?
Challenge 4: To Subclass or Not
Create a subclass of StudentAthlete called StudentBaseballPlayer and include properties for position, number, and battingAverage. What are the benefits and drawbacks of subclassing StudentAthlete in this scenario?
Key Points
Class inheritance is a feature of classes that enables polymorphism.
Subclassing is a powerful tool, but it’s good to know when to subclass. Subclass when you want to extend an object and could benefit from an “is-a” relationship between subclass and superclass, but be mindful of the inherited state and deep class hierarchies.
The keyword override makes it clear when you are overriding a method in a subclass.
The keyword final prevents a class from being subclassed.
Swift classes use two-phase initialization as a safety measure to ensure all stored properties are initialized before they are used.
Class instances have lifecycles which their reference counts control.
Automatic reference counting, or ARC, handles reference counting for you automatically, but it’s essential to watch out for retain cycles.
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.