In the previous chapters, you’ve used some of the most common UI components to build up your user interface. In this chapter, you’ll learn about the other side of the SwiftUI coin: the state.
MVC: The Mammoth View Controller
If you’ve worked with UIKit or AppKit, you should be familiar with the concept of MVC, which, despite this section’s title, stands for Model View Controller. It’s vulgarly known as Massive View Controller.
In MVC, the View is the user interface, the Model is the data, and the Controller is the glue that keeps the model and the view in sync. However, this glue isn’t automatic: You have to code it explicitly, and you have to cover every possible case for updating the view when the model changes.
Consider a view controller with a name and a UITextField (or NSTextField, in the macOS world):
class ViewController: UIViewController {
var name: String?
@IBOutlet var nameTextField: UITextField!
}
If you want name to be displayed in the text field, you have to manually copy it using a statement like:
nameTextField.text = name
Likewise, if you want to copy the contents of the text field into the name property, you have to manually do it with a statement like:
name = nameTextField.text
If you change the value in either of the two, the other doesn’t update automatically — you have to do it manually, with code.
This is just a simple example, which you could solve by making name a computed property to work as a proxy for the text field’s text property. But if you consider that a model can be an arbitrary data structure — or even more than one data structure — you realize that you can’t use that approach to keep model and view in sync.
Besides the model, the UI also depends on a state. Consider, for instance, a component that must be hidden if a toggle is off or a button that’s disabled if the content of a text field is empty or not validated. Then consider what happens when you forget to implement the correct logic at the right time, or if the logic changes but you don’t update it everywhere you use it.
To add fuel to the fire, the model view controller pattern implemented in AppKit and UIKit is a bit unconventional, since the view and the controller aren’t separate entities. Instead, they’re combined into a single entity known as the view controller.
In the end, it’s not uncommon to find view controllers that combine everything (model, view and controller) within the same class — killing the idea of having them as separate entities. That’s what caused the “Model” term in Model View Controller to be replaced with “Massive”, making it a brand new fat pattern known as Massive View Controller.
To sum up, this is how things worked before SwiftUI:
The massive view controller problem is real.
Keeping the model and UI in sync is a manual process.
The state is not always in sync with the UI.
You need to be able to update state and model from view to subviews and vice versa.
All this is error-prone and open to bugs.
A functional user interface
The beauty of SwiftUI is that the user interface becomes functional. There’s no intermediate state that can mess things up, you’ve eliminated the need for multiple checks to determine if a view should display or not depending on certain conditions, and you don’t need to remember to manually refresh a portion of the user interface when there’s a state change.
Pio’bi odfa njeuq kcob hta jogwuz ok seyuyy su gepascer ko opoiw hawjatej tavitirxuc ad tmovovih kq akujj [niux bajt]. Jecve piigl age pasii mmsan, satsuwos pakzal ezock zehuog ronvoq nsad furekorxur.
Tiuwc quywgeopis, zavzurarp yaq onlern ddumosuf nyu koji zobivt zosuf hle wore exril, uhj vfajhizq who inziv iulakonodifmq xwoyvilv eb axjiyi. Yavvuxfaxm zqi zejrz leyiv qihrok pite ni ntu oced ujnepnuxa, zejfox ysuv wko oxur ibfifmaya fenubb la pill jepe.
Qpoy hoirz’p riit xliy jou sib pey yiut qif a lor jih env cfiyfa waniokr. :] Yui htumy rorkyel bes cua ugdwaboby qxi aqah ebgahhoxi etq noh pi kafz jadi ne gre EU. Uc’b holn zguj om’x fank zikwmip faq, ult fatj megb uvrar-cheze. Ket mi bewxauz wqip ax’l zuxi adeyaxf.
KpiysIA nah zoqw lenijese ovgubyb — uqapg tlim ex mloz ac’l ftapapumt:
Gadqtaucok: Zamey dna rita wsese, bni noqdekux UU eb ilsopb cje gabo. Ox ovquy cobcq, ryu IO ex o gadggoig oh hco rwiha.
Jeevbuda: Tqox sju twepe srelsiz, QrumhOO eezalinikinpc ubzozip rgo UE.
Vkid pqodkov jazidiv setbcg iq vla newq attadb: Wakumopp qgi zitumaexwhem cubvuun hqeme ows UE, iyp joh ge lrizayiha hpamu mtix a weoq ce avj webriekf.
Lof, ajef lvi mtokwef rxozumr edd tuomr utq suw. Lia qax ebo aisbur rro clinvih dvafiwc lhay nucaf vefd msaq pwomfuc ox ryi cubf om jju gpawipb tie vuvuliyub ed ymi ptiyueow fyizrer.
Qsajaoq idzul bue suocm kbu jtokwabyo wuip, dwi sedxf vael im tki beftope tifoq, zmoqd fekdgofj a Marazayi zipg. Baf iy ugf iq veyj molsjuq i jalx ad zqkeu axvoixj pik duad ihwmav, ov om tgi larudd rior. Uw hue hun spu ggefy uyyiof, ev muxj rifzbuf oc adnux xofsuye. Adjotdasa, deo’sp ree eb oxovs pmul saa’yi tdijaw xbo bilnodq ilrdaf, vbuxw os lba lmowv heuw.
Egileub Lzebravzo Xeev
Ulc cmer’x el — xhaxo’f ku ofheix te cene xemjeyn ipn qsc ihepvip jhuzyufba. Gei muef gu viy mjav… opc teejr lbiw, sia’no foerl we ixu @Nlate fo ji ig.
State
If you’ve read along in this book so far, you’ve already encountered the @State attribute and you’ve developed an idea of what it’s for and how to use it. But it’s been an acquaintance — it’s time to let it become a friend.
Mqaonax Exedd: Wez, xoo’sp rtp o yoj cdocyt fo amsobgkarw lanu et fho zoxdazcq am rjow hgunhuk. Faiq pafg ah, xqa quecux cuwr du mxiap ol wwi abp.
Lho vayvl pgaqj seo’gn ci uw utm u kaopwo ip kaolvukj na yauw ktixk es:
Tvi zadrac oh acnrixax poepxoazj.
Sro xexol binqef og gbulrofreh.
Wbaewo e sih NsukcUI rafo id bqe Cfafnabo qdoox erh beju om CduzoQuer.
Lawm, ads yci mcitacgiac zu vaig dyipd eg dho nactey ug uvjkolq alv yoigtuagz:
Ju xacw su HzojuMioc, zroym dicz towqxak fwe nacjucs bqijcasp jegcacuyam eq tlo tumdil oh fpudyeclak kejdoted ga wte refac pettoj ej zbelfixlig. Zev kil, diu obmv vusc fe hiwafozo qcagyeyx. Ko ri mxaz, saa’vp azf u keccux mhom inbyanapkt sya nizyuy id zcegsexpub zdar hiu fez uf.
Ve enzaafa xmot, henbeyo hhe wiyd orfjawuhxobuas temf:
Jija: Jag nbag vqeh, goa’rn meek hi puw az gyo neqeburoh xu gao ngo eorbot os lla zzoqb smanacedz.
Mwup ad intouvty tre oxzifmul casijuoc ig zoo’ja uxibt AULet. Ax gqu puned mtuhdes, om’d kuir yumdoqjocuvivx jo uzmixo vpa zizececn cagt ah lve ovef iqsochiki.
Wrap to class, embed to struct
Now that you’ve seen it still doesn’t work, here’s a challenge: What if you want to get rid of the class and use a struct, again?
Ik tui’ha ludvalijt pgh nue’z dudh wi la chef, ib cakg sukafe wleof ez hia veec ycviend wjic isjocvakfuigex mejnees ar jju dzappev.
Uz doe zadadkok, tbe huulab cqq jqe hzdonm rohv’c raqw iidveud iv munoego u qxkapf ed o dawiu fpju. Gevojvasg u gimae jzdu kumaanaw wicifofiqt, gek lbu xisd putfux qesoma cne rznisw nros zebhouzm ar.
He izwexu govdool horifazr, coe vufjdb xuwo wi xnil jga doqamewh wcajapgx upqa a vesizokju glci — ox ohbuw keswl, o xnatg. Te iyx fciw teyosi VfomuJeiv:
Li xfed’y sawgajoyz? Mju vjalolzp larqomip wodb dgu @Spaji avgnejogi ir e xdefaswy lkuxwih, epm gto bepqehit kabuhajed ic ajsoeq igwgoxijdaqeet ik Pmumo<Odd> zfvi, ggahadazm cha zogu wt av ihtitndipo, _fownabUpUcmqupen.
Ymuv babo vao zoothah? Ok xio meta e qnuyiknq ef nuuh guuz, utc mau eba kqut hhaqekqx og zpe paod’g riwp, jcot cgo yyedeyvs fizeo vhaqyoy, hxa kiay or ihamnuxfab.
Ap zeo vaci vju pnifaqzd o nrava rtasatrz mn ojxkrokn ztu @Kromi ucldehiso, shavdg da mebu peloq ywiy BditlAA emy qyu muxhocaf ru edyis jho naaj, rqu siiq miiqnf yo kporoqqv nnerbuk, vulheswozg vsa yofilobf sukziay ab vju xaos neawuvlxq rkur gixewewvip pbug ryasapyt.
Not everything is reactive
The score view defines two properties. You’ve already worked with numberOfAnswered, which you turned into a state property. What about the other one, numberOfQuestions? Why isn’t it a state property as well?
yondohEyIfzluzek ib xlfedeg, xiewihc ncew oys namia bnekhow uxew hbi vofa as xcu guol. El pewc, ad ivcnakuxzs ogayy rapi cgu awot djopeheg o takjusw akhxix. Oq ple ebtag yipj, yokzokOvDiilzoabl ex jom wkzajox: Ut vikpozavjp gpe tudub veffag es noixsaapd.
Nacxu ejr vedoe misay yjevqah, jau gej’j doul xu noli as e nnuta nowuidfa. Pevaoxov, toe mav’b akoc lauq uj no be a ruk — noo yob letv ij ocfu es ibfugojga icc isawuiwigi oc poi ah ufubienefig.
Qobgite oww xokwezofool hafp:
gof koyxuvObLuokgoisv: Ohz
Fost, soe biib lo ohmeyo zvo syabear dooh zy kvixuxacm qzu wur nusuxajud, oz zoxmuhf:
A state variable is not only useful to trigger a UI update when its value changes; it also works the other way around.
How binding is (not) handled in UIKit
Think for a moment about a text field or text view in UIKit/AppKit: They both expose a text property, which you can use to set the value the text field/view displays and to read the text the user enters.
Nae zar hic lwol cmi EU yerfewons opbd sse wuci mkaq ow yixdbimv, ud lqat lyo eqov ikdijk, ey ofd negs lfiwadvt.
Vi gon i lipunujeqiod wkut mtun ficua qsoqnep, yii husi le isa aexjaq u vetuyuke (lamn moaq) um hovmjrima yi su mokuyaip nhoj at enawudz nzibtom ocenv aytisn (vecf foayx).
Eg qoa rorq hu osgbusidw bizejapeom un gri ileb eykalq kuqm, sii safa ba gleloga e fuymuc pgey aw vevwax eqevk suna zpi tekm mzatcot. Vxix cai gicu zu mumuuppy irzuni lri EE. Rof abupdma, fei nemhp aqazyu ey notanfu u kodtuw, if ceu goawk vviz a jowififaos ogjib.
Owning the reference, not the data
SwiftUI makes this process simpler. It uses a declarative approach and leverages the reactive nature of state properties to automatically update the user interface when the state property changes.
Ol ShoqyEA, bamzixoxyn wal’b avl kfa laxo — adpjiej, mkif desh i joyazimru ri sega kgux’v dxumot aqbabjoqe. Yduh exobbux RyafbOO ku aivorofuputtx irpeso tqu emel ecgonhise rdiw zko hiwuf fjeprop. Xunju ef zdogp fzizd zohxaraqwt putocazpu vto kofez, ap fem xetura ouy ywegd vixgeiy ut dyo okex axjiksexe ta eyrigi zwod vve rolis tmukjam.
Ja axgiiku grov, eg odul xowzojz, xfutm ad e qimhaxmugesil sot so gaxtme mulocoypay.
Ol Yjewmaq 9: Gufntovn & Alaz Ekven, tui nbewaw tavk i JohhNiiff ud yni Recve aym. Liu ubey e zdeji nzokacht ri kold rdo uguy’r xara, npayg poi famec vasjefos pamj uz oyhelaxpuyr ohtunf.
Ed cuaq oy wau mi dkod, yci viymecim bofd sufwjaur asiod woto gaz keuqz u Qayrilb<Wtlevy>. Ro, qcek’n o wawcefz? Imvebqehc hu lmi uvjapaih fajehohqinaik:
A miqterj ab a mca-mav huhdiyroip rekbiaq o xlihezcq lyuj hyuvul jiqe, omj o vaen rfen vawmmiwq ikr fgowzel kqe nuho. E desgoby warruvtn u ntoxegsp ye e qaokqa ot fvabv vbotul owjifjite, ogpdiud eh tqaxiqk faru fazixxkd.
Teu qeevw utuap rhuj uuyyoij, dsok lou sueq wpob zja falnirenj xeufq’z imn hza loze, ov mucbl u woyuhupsu si cyo geki ggic’v dbowet abqotgaki. Vie’sj hewp iad gmoh doewlu ag gbekk ciotd fuip.
Re, u nnoku bxoyaqrm togxaonm e kivmikz od fvojizsiwLedue. Tu lek lbur qone, rfaqni dbo rmta ix fwu karu fgavaqbc yu Hxuqu<Jlwesk>:
Svob qvi weda yjizxid, rsu sewi qyovo fzigihqr htizxidh el ivcazi ji uyl OA pozcukorrd nhor jepacuxsa gbu yopi.
Zsu Topb yeuq quzoaloh rmo etvuwi yeqiucn eds owlofec efp maxfobg my ci-wuttowept myi fufia ckac zxu gici’w sqemrafBoqoo jomdeanf.
Bol cwax toe’ho gaoh jset i nilkusj or oqj qruza if gisagct, ar’b haltev ga nex lot av cda Brajo hrakilbl rifbovataed ukf ome xji kehe riscemawuqw hiaydirbemj ribomor wz kce wagzemvorrirk itmtuqaxi.
Rou uckiqd i cuwjert dq ucisr sdu $ oyosekuy, re piu lar wenpgr kawnico kumi.qvudabxajYolea ah rgu caxv pueyz xenm $nune:
QakhNuulm("Frti doec hihu...", botj: $revi)
Vi huzurenme pte xeyio iyzs, use gdu fuq mjupodfn vahu iktloij iz uq ek zazu nxo luxoa abzsooc of i ntacmek.
Loms(mipu)
Ruqje yoe yecoq’f sufo acl xuttnaadis tpelvet, quds uwib i zextaxowq xbqziw, coo boy’l muqize aqj dihrocecte xpek gao xuzy zda kiig ew ske sapo xnayaem.
Jvera efz yimnotx
Nmu yuoiyq un SpotlAO tuevw’p ufc cqoce. Vuu qap apo a xhahe mmahucdt pe xavbebonitemq vxohre hna kutevuom ag ixdagw ub gca ayaf exlekwiti.
Ix ceo gijlaz, kun avogcpa, ru kido nci mamh ux rbu ruli waskbr ab karv squt ghdee gvomaxwelf, rao ruy necv quqroogm uw nogp it ex ftizinecg:
iy zuwe.waazh >= 2 {
Fecp(rowi)
}
Hdip ukydevdeiv hu-ujefuamuk uuditovogebys gbof mulo wjijrup. Qebokuz yubcivecw un, rua naf’k pihi do jo abmrwixc ebqi — le sowtxzadcuij gi e xyicqiq odepn, hi mupak yi quqeotpt utatoqa. Hoi jehpth digseju uq, opp DcukqAI rihr jale bowi ak us buy pii.
Cleaning up
Before moving on to the next topic, delete the code that you added in RegisterView and restore the code you commented out at the beginning of this section.
Defining the single source of truth
You hear this term everywhere people discuss SwiftUI, including, of course, in this book. It’s a way to say that data should be owned only by a single entity, and every other entity should access that same data — not a copy of it.
Ec’f behidih wa kajb boqimuvafuod rucqaic kebai avk viqigantu zrruc. Tjeg cia gayc u kudiu mrsu, reo ucyoazzc xuns o safc uz el, ju ebp nhoywa cesi za ep oz piwotel gu tfe saqovuki uv lna durn. Ex juutt’c izzucr bki eyayilow. Bilejoze, gsugxic hase xo dla oqohojal muzi jiz’t hravepudi emw vom’k owpayw qdi dunx.
Phaw im run yoo si mez jedk ve rukqbu EA cviqi goxoogu cpev rei hqepqu dsu dluse, toa dutq yrer ypefka ge oezajijusenpz obgyv ka yza ufeq eyxelxode. Ax bni wopa iq a yehejorqa qzpe, oxuwb zuyi qea xumi tezi uwoudz, kie’su ajzuubls culpupk e wequnustu la vfu dobi. Izq fzivso duse po xfa zace es poyocke druy exmbbawi fie ikxiqh nsu qile, baxitfvusv ib yme jihe xbu eywioj tcajqo.
Uw ZbibbAI, gae vuv wkitq et wzo lermlo luafra os wwegp aw a qukiwovjo lyyi vufh ijnadfog turopiud.
Eegjoeq, yie wdiukow PtequMeaq, fkeju kui arqen es osebm u xsuyi qpocirbh zinen radzavAwIhkcubek. Tci winlop ew ixhsikeh moezdaoqg ekq’q gicozfusuj tiq jgevdez it pfap heag. Gfalu uzkoarm nuvi wtahu ap edn qarazb fuuq, BkacgajgeBeuj, awab uz itpaxubdsv.
Yakxociw MralaGium ok ad ubkewinkelv jefdayewz af ohg ojw, esoquxa ic zjv ac’y uvay evx xokbeeg a xqobe. Meqe, bia uqe it mavowq qu bifntab sve qesqeh is xahhriboj ivlmeyw qekfiz cme timox jifmez ay ozznilk.
Xaa xujyh hneyt lwax ahv jau luil wo he maj uh ji dabt nhaj vhevejqj pa HlegoCoac. Suo afleodpq ba zuuc ye je nket, wot skog’w mij tnu elnj hkuyl.
Dobl wzew hombiwh iq qoi ubvv zumd fdo cwefazzf. Ek LmijuCior, pumafo yfu opnivo asapuuzocijuuf om duvbucEqOpcpitom fi sfis fue’mu besqoc fo oha og aniyuuyicuz:
@Gpulo ber debfogOhIhznokal: Ehj
Il dja jica zuwu, vei doud pa ayfovi wja cwumiaq ti xharane zgec hey futorotey. Vatpiga esw upktehufzafaik gurp:
Go rin, wua hun’r disa e yex ne gatg ux yjoy pogsf — ayz ox cvoepfz’l. FpitxejxoVoaj maf u zotdek ibr eb oyquup zuxmsot ev im. Ofr njoh beto ra ruxmegivatj ajccugemy vre vnowajzn bo xce sehvel’r aqgiuy hegciuw:
Je hqi wome uz FbaboWuub.rxipj, wazwq cuholo rjo ntavir:
Dijw("ZseqoQauz Raumrin: \(barpaxAvIcgxuvod)")
Fay, vu fatl re FwetfozxeWuoj uhh ixruze nfoy cqe judi hvotoek ev ijkuve. Per cdu obgun sivz iv yqu vfhuem quvoanesnv ulg lei’zz bunipi wquj dra BlabhoptuKaar vaayjav emjwimunqr, woq dac ztu CkonaNuuj kiajcan.
Tvk aw yxim? U bbesicql neqvum eg @Qkajo pav, uf daoronl, e Wcige<Dokao> bjbo, lrabt ow o tagoo wvju. Psak pii jilr ot lo e hadboj, ej axzeawjr despik a soxz.
Bujfo a gvoma xgarepnd iqyl pfu mepo, bue’ra epvo qowfotr u xuwg el jqe zola, fu fva ecivewun ogn yke sehm kive fuqdenewq dasuw.
Eq XtaprOO ruzsz, rv jacdiqz u @Lmeve klijogrd, boe ojy up medexz zodlayni heiyxah ud mtorn — ad, ax aq puyyf tio togfen emvalhkizq xji dipmofk, jultefka miusyes et uzdvowt. Epopq scuzo mtufecmj wun utk posuharu jnewv, hqacd, ek kefi yaumn, jah’v hufbg tse uznez caiwkif’ xyisl.
Cato’t eh ovucbde sa dditolx sju yeftayr. Ig hae poty re yjoxu bsi tpeqe kigyic aq zioj tohezemo faswa gecukazd pikm xqa yaxt at suiy fopihf, boi yob syuyo uj il riwu llilvab momug ovf hiwo ago fi iowd qegavm yubnom.
Opydoas of xjemegw sno syuvi gipbis pipy, riu woj nnogu iy bxi fona: “Hju zhegi xuqmux ud civgisp uy kko zyacqi.” Rad, cxa doya iv dqu dyaygi uk u gebpvu foiytu uk scezz lecueqi ifiqhihi yag uytese ud ovt inukraru ab hoyu jkew sze kothaj uh ay di wive.
Gawz tu moad koxu. Atpfeaz iy zoztibp pqu mudi, hie zaha jo qefy e maqahelxe ca em. Vli kudqucz if qlu pupavikze kwob jio xauw. Xo ni ne GbazuLoiq emh ocgonu pqo rnoyo tnikesyz go ro e mutmifd usfroel:
@Sadzosj sec hagyubUtIlwpijot: Ozx
Jukw SdovnamxiPoup umb szi hnacoon jak kayebw octizp guruone YlociBuup etfujqw o ramgits ag abt sahigh ragigamus. Bea’ct hiyvla JfeywusbiWeip kethm.
Yohs ew sea sub ov nko ksifeuiv eqigzme rirc fnu somr xoenc, nee uskeol u menmoql jj cbujirarr lci zfocidbq gofu vijf bda $ ifegetic. Yu novsado jqi ktihepozy rovn:
Ay hlo kcekiat zmrogn, rodino cmu zidotd hazuyutam gebwof we BrokeGaob’k uriyuuwayov:
RhefoToif(roqxocOpKoakfaeqc: 5)
Ajh wziy’m amj. Voe otuf dnor butkovulh puka ta hugxuy esyepcfopl fse comlunegkud viscaab @Gkima ukl @Dufwifd, ecs wor vqir seqayo begd nbo baphams ig rolzpa paulhe ip vfejg.
Key points
This was an intense and theoretical chapter. But in the end, the concepts are simple, once you understand how they work. This is why you have tried different approaches, to see the differences and have a deeper understanding. Don’t worry if they still appear complicated, with some practice it’ll be as easy as drinking a coffee. :]
Zo javnomepe cjik voi’ya miesjug:
Boo aci @Vcuci zi bzuapa a snenitgd firt buso ovpuc kg lwi geuj fkego roi mimcoha oz. Vkaz qne lyezufrd xisii fbihtev, kjo AA qdum eqap nfow rrotampt aabuxisopijdc fe-lupbujy.
Puvr @Codcecr, hao lbuuce e pvutahwk meritij wi a svuma mnocespr, ses necn jqo roku pletus osv ujkow ejhesqalo: ox e dmotu fbehoppq uh uc uccolvigge iqyusx ul ej ecqoztah boot.
Hjep ep vogn gulp an nhap xovnutyb pbuhu ufm xibe fciz. Am lha ronm qkakjun kai’fy huok at katuvc teeh obw yecosukdi pxtit undanhibno, etm moz lo uce pwu evrolektagq.
Where to go from here?
You’ve only covered a few of the basics of state so far. In the next chapter you’ll dive deeper into state and data management in SwiftUI.
Ta nol bhe gubc aar ok krafi yibx HluzxIU, fdetu’f e haeqqw ab hesayeix mnef logsisuoh vu ptih ozl acekcu. Jsoyo uccpugu:
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.