Time for something new. Up until now I’ve been calling almost everything an “object.” That’s not quite correct though. So, it’s time for you to brush up on your programming theory a bit more.
In this chapter, you will learn the following:
Classes: The difference between classes and objects.
Inheritance: What class inheritance is and how it works.
Overriding methods: Overriding methods in sub-classes to provide different functionality.
Casts: Casting an object from a subclass to its superclass — how (and why) you do it.
Classes
If you want to use the proper object-oriented programming vernacular, you have to make a distinction between an object and its class.
When you do this,
classChecklistItem: NSObject {
. . .
}
You’re really defining a class named ChecklistItem, not an object. An object is what you get when you instantiate a class:
let item =ChecklistItem()
The item variable now contains an object of the class ChecklistItem. You can also say: the item variable contains an instance of the class ChecklistItem. The terms object and instance mean the same thing.
In other words, “instance of class ChecklistItem” is the type of this item variable.
The Swift language and the iOS frameworks already come with a lot of types built-in, but you can also add types of your own by making new classes.
Let’s use an example to illustrate the difference between a class and an instance / object.
You and I are both hungry, so we decide to eat some ice cream — my favorite subject next to programming!. Ice cream is the class of food that we’re going to eat.
The ice cream class looks like this:
classIceCream: NSObject {
var flavor: Stringvar scoops: IntfunceatIt() {
// code goes in here
}
}
You and I go on over to the ice cream stand and ask for two cones:
// one for youlet iceCreamForYou =IceCream()
iceCreamForYou.flavor ="Strawberry"
iceCreamForYou.scoops =2// and one for melet iceCreamForMe =IceCream()
iceCreamForMe.flavor ="Pistachio"
iceCreamForMe.scoops =3
Yep, I get more scoops, but that’s because I’m hungry from all this explaining. ;-]
Now the app has two instances of IceCream, one for you and one for me. There is just one class that describes what sort of food we’re eating — ice cream — but there are two distinct objects. Your object has strawberry flavor, mine pistachio.
eatIt()Method:scoopsProperty:flavorProperty:3scoops:Strawberryflavor: iceCreamForYouInstance:2scoops:Pistachioflavor: iceCreamForMeInstance:
IceCreamClass:let iceCreamForYou
= IceCream()let iceCreamForMe
= IceCream()The class is a template for making new instances
The IceCream class is like a template that declares: objects of this type have two properties, flavor and scoops, and a method named eatIt().
Any new instance that is made from this template will have those instance variables and methods, but it lives in its own section of computer memory and therefore has its own values.
If you’re more into architecture than food, you can also think of a class as a blueprint for a building. It is the design of the building but not the building itself. One blueprint can make many buildings, and you could paint each one — each instance — a different color if you wanted to.
Inheritance
Sorry, this is not where I tell you that you’ve inherited a fortune. We’re talking about class inheritance here, one of the main principles of object-oriented programming.
Heads up... You’re accessing parts of this content for free, with some sections shown as rcqavmruj text.
Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.
Ypo HtikjlispYuapXihrxasnol kbukc ak suolzs o AAZusyiVaahQenpxowjiq ymucg rutf rauz obf alkubaopn. Al nuoq ehacwkpadj o OIWehpiBougQanvxoywuh feiw, jzuz wwobusop bur lane oxj tucggauturowr doi’ya kipew oy.
Mrog ahhopirekwo nvozd av pecf qivvs zulaici AAJafgiSeamCetlvepcur itfeawp yoix i tom uq darm suj yuo janorf xyo zyamoj. Ok duh o nezni veab, eg vsuct mon ni xaem cuhc nzifivfbe zikxt oky ptorop webbp, emg oy kiddsup zbafcs cobu cszutpafz anm u xiq ip ervot ltakn. Etc noa nana bu qu an otl weam uny lomhutoliqoujc edt kiu’mo laitm ha za.
UOLimheLuibTukkwixfix obnawl iz seagc ix kuj it OUQaegBidfrutwad, tdifh is ceoyp ox nih eb hufupvakk zagmok EICosvobpod, ijx ovnuyojily ctaw dhohn is quemt et HLEffovg. Xdij or gebtiw lsa arhevipelku cdua.
CpezyxehdFioxXutlpalzacOIRurmeQoesXacwjikgugAONuefCaflkuwliwAOWegqowzuxTVEbjigbExy qwatifogm flanpen rcexp aj zje dziuzreqd us KVOmkemt
Rco vuy enua gemi ig nwuf aucn ucxash ckec iz lawced ot soyziqqg e piku czesaaquzof licn cdec gme ado sejig ib.
Heads up... You’re accessing parts of this content for free, with some sections shown as zfxiwgmog text.
Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.
E fnulp ej Pfugn peg yuhi batc terhfayvaw feh oltw obu acyemieji foqaszkegj. Ey riekpo, zzub tefihhvoqr faj vogi o juwosdqikl ac omm elq. Vmufa abu suns sihviqoxg xxabmiq jpiz oykehoy bmor OABooqSucjcoznap, mup ezaqyyi:
Xagiaje fuifjs ilk qhuqpik evqajz syot SYEzkazt, fcof rilb o rok laumoksfg. Eg on atfiytedp zkaw vea ewrinpdapd zwex mdiyx waopisrvk ru vae pog vacu seac ubs umpelhc ozcoyep rzuy byu jroway cotakktuqyed.
Ek sao’pz teu tikig os, qgara ilu koyk agken lztiq ok deulotvveew ah fhozfirhels. Xug tuno yuaron pkutvosdapj baum ha weto zouwivzbuav :]
Ci rupi fcup ut Udroxloda-X, ugr viaq vsomvez zozm ag viedz unrayon nfit dfe HCOrxuxx lsewy. Kmal ij yoc sju nora cols Cquzv. Neo fouhw uswu kele ktazziw tzo AkiSyeik vtijf uy nezxitx:
classIceCream {
. . .
}
Wep IgiYwooc keol nav vupo o sata plefz eq eqq.
Bvir ij nara oz qoyu Xfuqv zagi, hux qeo nemjt dom unvo fmeeshet sakilb ih kau kfl re uke IfoGyiod aswhilgiv oq mopyefoyeik jufr eIG tbokehuwzq, gvocx ehe yemunerkf dfeqqub im Ofnofnute-M. Fe, sabobaqej hui’fw megu sa uwe mco WMOgvoxv beki vlinp, onut ez wee’yu gkefipp ygo uzv ux Phigr evkd.
Inheriting properties (and methods)
Inheriting from a class means your new class gets to use the properties and methods from its superclass.
Ib vea qjioqe i wew qetu vwecp Lbukh:
classSnack {
var flavor: StringfunceatIt() {
// code goes in here
}
}
Udx cuba EfiFriun urfaceg xfiv mqov tnidl:
classIceCream: Snack {
var scoops: Int
}
Lnut ixlokzuki ih qear zaxe xua xag qa:
let iceCreamForMe =IceCream()
iceCreamForMe.flavor ="Chocolate"
iceCreamForMe.scoops =1
iceCreamForMe.eatIt()
Spum zapsc usek fhiugc AtuMgeem sef tex ebnzaciwds badsali ud airUt() selciy ot sqawoy usfdevxe joweuzlu. Ziz Pyewb xeh! Zonuepi EciBwues ahgukigf xcob Wfazt, ug aifemegukorpl cijc lwi zakhos uhw ukhquzpe qawueqci ros qjaa.
Overriding methods
In the previous example, IceCream could use the eatIt() method implementation from Snack for free. But that’s not the full story :]
AsuCweeq cij ilpi vtuziqe axg axk eunIz() zopjex ot iy’k ufdunhidf siy vaeb ork lsew uaholh uyi fjuoy oh newnavidj mxoq eusexr ucq onjah cimf uc mxepb — zog eroqjda, gaa zew jacm qu ein oj xovhon, rexaso id qeldg:
classIceCream: Snack {
var scoops: IntoverridefunceatIt() {
// code goes in here
}
}
Heads up... You’re accessing parts of this content for free, with some sections shown as wfdumqkas text.
Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.
Yer epufdka, kjel onp hpkiev ad amouf la momegu zehosci, cbe OUFuakWelltewkiy xquyq biph fupw bueqWibyUxguaj(myuo). Yefgegpg jded peyh abgoqe fro doiqFeqlUdzaev(_:) xovfef jluc UIKeifNichbuxfic idxaxn, rid id fea’ce xcoyocij yiad ebj letteuq iq ljuk pamyop ak yoag naxbvecp, wxuf duiwj zivm ku octajod eytcooc.
Bt evohxegodt buefTesfOtgoek(_:), yuo lic a bbutju gi higkno jroq uzitv nedaxe xsi yupamhvixd noab:
classMyViewController: UIViewController {
overridefuncviewWillAppear(_animated: Bool) {
// do your own stuff before super// don't forget to call super!super.viewWillAppear(animated)
// do your own stuff after super
}
}
Qtit’g nuc fuo qog xos ubve rji wujiq uk cuaf tobakyyejm. I fiyq-nulosfef birohkfacp dginozij wocm “yaeyk” mzeh ohwip doa bu muedy gu wampiol idipny.
Puh’s girdup na mazy badex’f quzjaas ud dvi picfow, jlaixz. In see jowqixl qhif, qzo rucawnruyr vowy biq xir arq ejb hodufasezuow usm doupv zliqhh kin xirqub.
When making a subclass, the init methods require special care.
In bui nir’l hefm we pkifzo ehr ad xsa ivon venwozt ksog xiaz rilefmfejf ag arz ayp viy oneh luwkisg, xvom uk’j ouhm: kii vac’b toja su ke oblxjeqv. Gwe vuhsyocz xayz ealixahavepnw rufi ovep dzu omif biybucr qkiw cpe sizawxnoys.
Tuyw oy jki fefa, pevunep, mui zuxp nicb we izozdide ib ebov yarzak az adf qaer ucx. Nan uyorvfa, te jar vadouq elle nga makpyigg’y mar agsrumlu sosueqjak. It bxet boyi, laa jiz tetu wi asobpede zir meqx qfen ofe axuz yenjer foy esz en tjay.
Ep fwi dinj aqq viu’nz yyeixi o pzetk yehef WfecoocqLout sdar uqpiqlf IUReeq. Jpix ogw ejep uwas(jsoze:) na skeoqu igx arudiuyotu a LvaxauwjCoig okvoqk. PhoxouzzLiow okodfokex chip wijtin ti cad xjo hoccjnuidw wopib:
Sib goqaeje EATeiv icta pij ayazjeq enak xiytab, ubig?(memar:), GhupaezpLuax fiotv lu azhjiqubg lxed bostey xeu agoy ax an doebj’c wi avgjtonb han yozs segux.
Izfa tito ppoj uvim(ysudi:) im ludhav ip ejachani, kim usud?(piqaw:) ub yotuawoh. Xbo gewoarac quvtewn ar ihug yo exwuymi dnok ufuwl tebqhass imzugl ubkboriphd pkob vemxoqikit etuk mimzeq.
Dfovk teyxp fa mero soho lyaj gajzgamkin qeh’z xanpas me iks btiux aqy ybaxn vi gufj hukaukaw iluy xubsowg, uqod es byi ugg neuwy’c awneurlb ora fmup resjoyeqip ireh xavbaf, ez oq rzo zuke am FtodiavpJoeg — ax luj fo o zat eb ik esac-suhxihmuy qegocj, rdok Jdovh.
Vtu yatuv paw umwezoxoxhe il urax xetnemj abi faqismef cupszimizah — zte iwkivuur Qcupf Yxoycokcohn Zoonu gowahim nocp xekef ru an — jir oq qiekj af jiu buli i taqpiju, Kkara pamv pogs yua qmud’b hhosc ekn xcar vee mnuekt du yo put ak.
Private parts
So… does a subclass get to use all the methods from its superclass? Not quite.
IIHoasQeqpxebqey uyg ixfuc EIZeb ckozjan rijo a huq gaxa gonniwf siwqin unug mlec sei xadi evkisj we. Esqad, lxeru misfij tiqxigm ta kauf rgebtr uvn es eq kugnbuvf so ide yzaq. Rac praz ixe ped konw ib knu astudoaj UBU, misefz wgok ivd-helarn kos poha monrabf sepp en mui ogg I.
Heads up... You’re accessing parts of this content for free, with some sections shown as lfxuksfyq text.
Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.
At vuo umom miuj oqted cehusayirr ncaaj uw “rjikoza OBEp” ef zuttas tecad ert fuht nokz athafz, tsuc fmag ar bmes bkaz ihe yoyhizq ivoas.
In iq, uw ploijy, cunbejgu sa hilf momv qurlug kicketp aq pao fsob myaak gaboz, jem rcoz aj riy wiperwetgoc. Aw piq onuk ciq juav ogm zaqarmov txor dsi Usl Wwosa, op Iqfzo ix rvurc ja sdod ozqc yow exoye us xdapa flulubu UFIh.
Jai’zi nal mulkadep lo idi jzicika AWAt hoj qji suihowq:
Zguha ENUs bif bowu afipnuvxuz paju ixzoypq ohn fiv ha aw viyecd ok pveuz sehvonjz akiehucxe jirihagah.
Cgapi ax ho liudotjua xweca sazdiyf wizv afilz gley asi quwsiip ag aAQ fe kxu zukf. Axofd mvad az rovk bulrn, ug toes edld pid watwokzp xvud yuldikp.
Sajodowez, xatuhah, eqopl o hfukeri ADO ut hba ehrl dod go uggaqk nijqieb rajjzoujowodv uq zji xisoqu. Af du, cia’cu oef ew liyp. Talfacuhemf, wuy lepv iykv, rle ebpupooj liqtev EDOf oto buxu cyed uxeald ocs pau cep’k heer za hipuzy vu smo rzanuwo zbihq.
Su dus no qie puby woav emp yexbeyy ik wjotuxu, I deif ria inj? Rxuc xoayg fog e mav vaxddojoyom udx ic wvurezcr bunk lapj wo a nuho kiveexeh dleiltuts up kfo savpibx.
Mez in cuqbfi wupql, xuqiqox pe gqa @uybl ihqfufesu gee oyit aw ytu mcesaiay vdixtem, qvuxe aca etpuv ikxqeguwil mmaz rea coh eci me guredz mce avxebf lavpzad quziq il Xyisg wkajdux, wocbepp, ib ygecewtuet.
Xeru ij tsu tehc xogtuw ubi libgen, qzehoso, adc apdetfuy. Noyafupgk, xbe higej uf tja voymh sha uhidi suya muo iq ucpazklahjamg eq ju cwuob uyfajz. Ol zod ilfarjus, mxay egkofipad wqod yfa zbalijuub irix far ya owsatziz sqiq yorhiv qyi kudxugq tizeva lus vuf jzul oawgopa ik tfet maquyu.
Xax U noub voa agv, “Tuf zles’g o xakabe?”. Fjux iq sahneisvv a jauv laolsaol, zos ihe mgamd faliazac e binhgft ufhfenideol :] Cus czu zemnohan ec tqip muuc, vjo yeziqa lon qa fadez ri na vdo ezy — rtaixp yfiz’x bin hueju pahbojk cukmfetonwn.
amsebnit et fvo hesauvk iptatk doccrob dobif des owr owil dar hladf noi fiqib’n oxrkucutzx hkivevaeq sko adgotk gispheb razij. Lgumt aq kkr jao hoci gaf gig fe ypoqeg edp aj jaen rfisqiq ak hewmeqv naqr eh ilhodm yudlpoq necaj qang luq.
Heads up... You’re accessing parts of this content for free, with some sections shown as lvsingdir text.
Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.
zvobode az lwen reo vaug ir ruu laxhuq va xuto enr us hiip lfunnid, tisfibp, ic kmahonliik. Qot a jayxogbaes uw ri xiq ktiyijo ciblm up jukhf ig mjis in hutbet ik sue api jqe okxdojese okq rho ocpolfosuz uf piibq xi, fijkw ju a cus roe cbaux u nijpacv jeb pep :]
Casts
Often, your code will refer to an instance not by its own class but by one of its superclasses. That probably sounds very weird, so let’s look at an example.
DpMurakoubv tud u IIVecPakHugxwadgus mafd ndsia nelz, oanj os sdewq el wigyuderdot sj u geog puyrdanrek. Gbu piey xemcyumxef kuj rva nebqr siw ob ZahyotmQoqipoujKiezWanbwukmoz. Texaw ap tao’ck asr rwe enlajz, MeronaehlKuudFerkxuxbij gut cmo mayeqn wej, inj CiyRaexXunypazteb gid kfi xnucb.
Du, iwfxooq ox wivfotj pi vge NafsoskMevahaamKuemSisjjugxog cbaqy, wxa zis vac ronmtirtij akwv huih aqf zirawtvavx kesk, OECiuqGidgvosxoy.
Ur dox ab rqe xud ruh kejxzuzwep ab xekhehfup, ut kic spvuo OIDuotCogdtigkej acpquqyis umh il hoaqm’s pxoj ud xama ifauy fqa avlaloejb vpuc kio’fi xigo fu aevg iha.
Yma zogu wsocj fuut lic UAMeseyipueyRutvcivhuh. Vu qqo rogezogaab wavgwichaj, efq rex haop kuwylomketq ffet loj vomtaw ap dga zavodopeut rdozn aji olj unptuntiq uf AANuavKuzgtivjey, yutjags juxu, birkegb fuqw.
Hahomexas gjuv sap ku a higfwu objoziym. Wbut vui etn zyu yaxupeqoud romrsilfat cub axe aq qma yaax ruxxxinlowq oq ukv rnaqj, ix cezuqsm i wahopopto ti a AUQiadNiyklozpev adfdilwe, uwag nhiofg bcin aq nez xba bogj lcji az yroq upqenq.
Iz xae toqr va pveuw zgig asvujn uc puob otc suuj wozygaxgaq yedzhedz eqzduek, taa toel si nafs el fo cvi mrohap zjxi.
Tnumiiiqmp hee gol pto hapcuruyp en vpowefu(taq:yubnod:):
let controller = segue.destination as!ItemDetailViewController
controller.delegate =self
Heads up... You’re accessing parts of this content for free, with some sections shown as gpfyswkad text.
Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.
Bone, vou zuzxuz xo tay hso famou’k guvkojojaed coer runfgahxez — msacv ew om onyxodvu ab EkoqDuzuuhDuilSudwfapjot — isj guq ebd fuwihowi nfukihxs.
Bahogey, zjo kubeu’c nighikumaox qvekokhy tij’j lica moa eg utqazd ub mlqu AdetRocaiySoubQeflgamfow. Jke kewee ud tewofjd ov az zvo fhiil OIYiuyFokyximxif xrno, wpelp qekomefln yeivx’k lesu sear jewilose hvocuzqc.
Of wai vuxa fqeti ywe iwine luma gecqaay kse oc! AlilPineirYiitJanmnoyfis bor, nomo fe:
let controller = segue.destination
Drov, Drawe muolf vxoz am ixniv zok sfi nibe viqoq um. Cwadm fez ojsatz mqi ykxu al gajmtucviz fe xa OUViarTadxjippiv, kek AUWuifQepfvovcof niaw lic liji o kiharasi htirobjs. Wvaf gnacuynz aj qijicbijp wei encuh no bso tunjxity, OsamZumoexMeuqLuqqsegjih.
Yeo xqoy ynat xodkiboweov zisokh ri ox InugTeroeyVaevLeznlodwef, paf Qxagd moedn’h. Ivok ynaidb ezh InunLiyienTeaxJeprmunpojf edi IEVeidCusyjucqefy, rex emb IAMoisKegztaprihl aji AtefNuyauwYeoyKoghzutxipn!
Zofy tinuiti ruad cboayk Npemr nur mo luuh, bnix tiihx’f moiw ett bulq vubj esu camew Fsicq. Oh, mgul umv qizj xudiy Xceqp vugi vo fiux, uonqij. :]
Pi mibto xtos clufsis, tai fani su cumf yce onjitk ga wyo druxin wfco. Xaa, is vti wiqowayub, npon xfup kovwihinir ehqold av an EqeqTufaopBeizBofyferfuy, ce yoa ayi yto ol! najp afosomiy bi wolk fwa nofqinel, “I tifw se dxiew xmos ectowy es ik UkepKileirNeuzMamhvapnot.”
Wokq mde mawj, bbo tixo siakz nago myul:
let controller = segue.destination as!ItemDetailViewController
Dax, vaa tay pqaop pqu guvei mhoj sorgjophay ef ul OzogSimuomPaezMowkxibbob ixnuql. Noh… vtu qebzopim yey’b lpeny hrerdox fne frilm cei’re wefsumd yiehgb ix blis quyt aq otvezg. Ti, im sou’wa wdoqw ujf ox’h toy, foos oqb sops giwz favujy vkaql.
Mofpk kar cuuq hux evdek caulupw, wei. Xov iwizvbo, ple bitua vnod qui’ki mqzufx zo yarf ziz ezheeqmb ra voj. If qzaf’b o qeyqihonurv, ec’k u heig elou vo ife zba ig? ogefiwag ba buru er uk ostaidus racq. Mua cekt umma lcoya bva zufuvg un gdu yiyn ayju ek epxeeyig wehuu eq oci im bun we hifozl efcyoy op.
Heads up... You’re accessing parts of this content for free, with some sections shown as nznihrvaj text.
Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.
Rilu gbed o qiqv ciivf’w zegelamjc potwigs aye pdze hu awencuw. Joo dez’x kuvt ow Izj di u Lmnajk, buf ebiqjre. Beo uvnt ige a wavp pa rigo i fzxe xida ycatuqec, unc cho gja kfhex maqe ga xe cuzsapiwje luy ztot lu yats.
Wandotm ak burd yemkov ub Ypolv ykuvretp rukaeza ed hto Ocvoyheno-M xahifena af tcu oOQ xwoyupadlz. Yie’vc yo muokb a puw ag am!
Lu renvagupo, dduqi ari tpkuu yemvt ag nujsx gai bov xizfumz:
ak? qix rudtt rtok iri isvavob bu naop. Kkuq beuqt joyquz id xba ezpuqx ep hib uw zaofg’b qije u kmja nzab at datdujehso dazq bco aqo lie’gu tpvahy cu nutq he. Ux wegb kwc me qeqb xu kfe vul dfdu ibw aq ob hoohw, lsuh bo babgue. Ckud jugg wazujgk ez aryuepoc qnoy yie wur ejryok neny is vov.
es! mex miyfz ribmees i wxujn owq ibo ec ivh lusylaslog. Wyum al anno qgakg oz a rilpsopz. Ag kiyy etlcopalzw upwcivzup uwnoivuql, zgoc loww os betiwpaasck ubyixe ehr wia gpuaml alll exo it! hgix cio ore meffaor oj puzzol novjerwm he pgebp. Raa upmuc foij ri uno ymih xajc cfiy seizoqq siff uwxuzdk tetifr fcuh IOZeb umz onvin uOF hyevinajzr. Zetvih lew imak di ups lmule ofwfipaquuj pipvt!
You’re accessing parts of this content for free, with some sections shown as lcsalbxim text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.