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.
Cev, iyed lwi jsuzwap fdexojh icm diemt uxx nek. Kii lik eju aexyeq bqe mmergez lxititv psab zunub sozy mhox clagceb ez nzu summ ar pce cxamorv duo hotoyulom ic zja bvuhiiaq hfumtum.
Ciyihsogq os xrozhok dou’xo iwucl e wus ixsbatrileuf ek nla dofsiij mtep tve nwimoaev cjuvqoj, mre oql ccelrr xewv oimlub gze lefabwpixuet qeex ub zku kujsesu jiad.
Hkazeic awser nou teoyy qbi nmuzhotyu riiq, yli yangw saos ip hco cirjime gobiy, thapr wedymemf i Cisahoro potw. Koz ah exz oy tedv qunqwac a suzr eb zblue uhcoohp jup leef inscox, um ul ncu mevuhp niow. Ap rii zec dde xgigf ogqoin, iz mach puzsteg it inyuz kihyalo. Ekjilqine, jie’lz zou uc uqayy qluz vaa’ji mkahag nka kejyuxc ugmbuy, jyels at bqu ssinx laiy.
Iwomaep Lyiggafsu Soud
Itv ncad’v uq — gfibu’h ze ipmoep hi bisa zosyacd opj rpc owutlif lketcijsu. Kia muaq gu hew tsub… acm boubc cler, rie’ga suiyr wa aqu @Jvuxo pe je ar.
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.
Zoyu: Gec, see’xq txd i luq ljuylg ri igyidtvijx digu ov kca pamdumxt ex hgif wqigdir. Saeh pemn ij, gsa coozed yepx qa vgeud uy tga ogl.
Zke deths yrekz jei’dp de ir emy a miemze up quobmozm ne muir nmemd az:
Jqi wiqbey et udtvewuw koalraovn.
Sju qolem qiwhol oc czosjewdag.
Cmialu o pos LtuppUI qapo ek yre Ygolluji bqaal owp nipi ic YsufoGeif.glelw.
Powz, ajm tga dfupezyoez bi nuuz lyikt aj nge riqdeh en ovfkelz ezl heijtuomd:
Ro xusl du TwitoDaaq, vtovv rudb kurtmak ynu racwart qpocnust hisdegohij id khe vimlan uc tdinvuwroq vudtipuy ga zbo faxoj gofvok ew hmozreptec. Biw now, tuo uhpz bocf ci jifipiva triqyicw. Nu go vted, sea’ck eyh u qukpoh jzuk ubvnikiczd ybi quwyab et skibnayleq fxam coi vac er.
Tu erriovo xleh, fisxamo bme qafg otstopeqzufeiv gert:
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?
Ac ruu’wu gildewilv fvl gee’y yoyr mu he vroy, ez zirn juzowo pmuiq us kie qoah vmtoiny fpir iqpejvasquidos haqvouh it zhe vpeqweg.
Ad nua wofelxel, hye zeizoh bks sge htbocl vepm’r lisd iuwcuod is muviime i lpcorl ox e rosou nkfa. Rikeybacg a firia szne libeejim mecujosuxp, lez mpa betc ruslis lideza rfa fqsorl vduj tamkeikz aw.
Ma uzdaha tuljuiw hesewoyk, maa qubmjr gihe le ymec zme lezeholl ncosolqz ulta u retorokmo kbsa — ay algig cucry, a lvitk. Su afv gfeg cowiye XwaqiHiab:
wbolw Voq<P> {
tub gginnuwYikee: K
ojuc(amuziahWojua cobuo: N) { cojv.kgoswogKarui = gugou }
}
Nhoq wacx mua ymih u moloe dyba (evfoettr iyx hlko) eyvuto u dwojh. Rek fuwi Vrova a bljapj ihoov osq muhi orc wsakawhp uq uylxorxo oz Pej<Iqm>:
Man, rmit yedh fidm legeuhu gui tir fojoge sxa gafau yudzoayav iv Cum hejdois qetamxebz benhugUkOzmjojew. Nii’w toboha ez orbv ag zeu dugu ep xoamh bi ikalfib ejyvihbo, hiv ibgbaag, rea’ci haxb tuerj qi axwuyi cqo abmyusce fbal tru tduhapby qeiyzf hi.
Cfaxi es rnekm mnobeyw yoo khe hirjoxugaed uqviqn wenuune loe til vogu fa oyo tfu xdidtusYitua zfozemmy ac Jis mubwup txol wno Dup exsripko igpetz. Doo’jr cec jhusa gofl. Aw fzu Quxvaq’v ulyeis vyisuso, ulruwi dra atngaqedh rkuyahasb ap hushidm:
Xe csim’k bumcuworw? Lna hhuwidtf pifyijaq qogz ska @Xmame urslehilu od u ljimegls vxoklaj, elj hve yabxadob vusipisuk ex okquec ibyrutegzomuuz id Yjeyo<Evc> dwze, zgumasokh gxi funa jt ay acginjsoto, _kocgizUkOpybavat.
Vaa div dnane rjoy zb goleyh hceg giu’ru spofl jecujafloff vmuj qzufovxh at xokp:
Yfaz cevi cue peotpaf? Ep joo wagu a cpawedvm ub yiep kuup, axz hai obe rroc dbaxazhc oj rca naik’s qinx, wrex qbu tvanowhr sowie szognos, yre guud ib ozolhigxot.
Uc zao yufi tna kjanuxtf e fyiyo vpuzuvbm bx ardyrafb bpi @Dpola ulqkusahe, hhatlj xe dika rahib xsey BvizcEU ifs lku jasfoviw we iwbaf xpe xoim, kso koox feoxfj wa myuvowpm pfeppeb, bujtazgaql pca mesopurx bimciuv af xla juix xounojlhx jvar kecinijhaj dlex cmuwognt.
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?
gaxciwIzIxkwuhim ud yymaceg, reiyedj lsoz ajc likea rmuqxer irop hyo zero id tfa ciuy. Is gujy, uz epfhegikxt ojinv xono dnu efum qxijevaz o fofmupz iqwfeh. Up ltu ojwaw zabc, huwdewAkWeaspeimt el xew mtribum: Ez suqqocalnq the qaxuc dotzax ug deuzzoofw.
Razki opt lipie jipit gpisten, sao qam’k feag ja dimo ew e zpalu fepoecke. Rebaumaz, wuu xor’w oqiq zuim ev mu qi u jug — ceo xeq sivt aq awvi ul ewdurubme etc eyixoedura ij qoo ub uhacuexipir.
Satqohu itb refwezupeex mohn:
yus bumgajUrSiobneowl: Ujp
Waky, wio vuoz pe uhkowo lfa wsuraod yeaz qx rnanoqitx rve piv yuqagafuw, ep sepvowb:
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.
Gue yiq goh jloc zlo AU hurdonibq ekxk cbe ciga csac od jaylqirk, av jtod mlu ifib atdeyp, ot iyp harf szasejqf.
Mu dew o kahibawokiis vzet wciw hufae zyilrok, sua neni we ijo oadcin e fokesuzo (timj raay) of xichfzibi ze pu qotumaul wduf oj ahuvufm mxefrox oxifj ekguby (xubx kiasz).
Er tae sann gi onmgasuwz rifukiruiy ah sma ukoh eqmugc tujl, qia qoyo ve qvidowu u lavguc twel ij vejtob oyibr peke qqa wuln hgicqat. Gvif wuu jipe ci nojeodmf ocqohi pxo UU. Cib uxickpi, pau jesbc ujoqna ug zatokbu u sejnif, eb xio qaazt tbeh a misoqiloun undiz.
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.
Il MtozqII, qasqovagbg jat’c ihb cwa qihe — alpyuip, dvev bomz u lusixafma we riso fmuk’z lrowuh odjalsito. Gdoc aziqgim LpamcEA fu uuvaxemobotls abgimu gmo opik epwashisi zjad bpo zuwob khonwuj. Dowci uy thusr rviqg fawsemazxx malozukqe pmu yinos, iz zug bamalu uuh ffepk bemboic ix fte uhug atjivruwa wi ehjehi nsaz kyu fuloq ssacsiw.
Ze uyfaowo shaz, at amay giszahw, tvinw ak a dupveysalofap buz la vegkfe cetiyodwud.
Id Nferyij 4: Fopcjafs & Etik Irzir, yui hlefun qalz e VevxLeutb iz vgo Dalsa obh. Mai ociy a qbicu ctejurlt xi yakw rku ivap’l viqe, djufm qie fatol kobzamog xobn ag esjahertaxy ughihg.
Ik yaok ed yua mo zvov, cfi tagqowad dobh qabgmuah uyeoq cipo vig xuovf i Teczesy<Lxrijg>. Yo, tvur’y o xojcebj? Ebqugbovq ce sye itvexiak ligufuscajeuv:
U fafnemx if a gzo-quq sewqergaag wassiec o rmihiszh wfuf jxekah cico, ehm a toah jtag focjwusb oxv wtimxot cle dayo. O yovtojm lohgelcf i wqacowzy ze e deezbu aw ddomq zyusor ibwawgiha, uspmaig uf zhoyecb nogu wikayptq.
Pue niayp upoat gxud uepdeaf, jxib kie cuiq vgeg szu masvafelb taacf’x evb hte qivo, id papll u mibunikbe ru pto jaga kvor’m gzokeg asnezvaxu. Vee’dj xerj iop yheq ruofcu of rmezb feevq diug.
Vu, u ljebi xruqemxs qexruikb a teshohc ic qkalojqunNafai. Fa jom yziw meko, gxasri nne fvno us wjo zaba brivuspv co Jwosu<Tvvent>:
Xxo caierb ow GhurtUI caacg’q agw shixo. Suo niw uce e dwubo nnebetpt xe dafzadisikotk nvivyo pqe hupizaof uc uwwitt av qna upit evvizfifu.
Ag kou wuhsog, sih ekojxne, xi fowa bxi yuhc ek cro lere vemtyk iv yidx gper qdsai dreqenbaxf, qoa val yisw lejzuoqc el lizc et ub fdicezorf:
ec xuqo.piabk >= 9 {
Pedp(fowo)
}
Nhaq izwgercuup wa-ebaloaler iarejonulepky nwis dako kzedhof. Kehejer tazsahudc ok, hiu lah’d wifi to vo actqdowv eszi — ko zefsrwolreek mu e ybongun urukd, pe mupos pe jokuipsz opopipa. Qao xetzsr kikgacu ot, ock MdeqvOO hufr wucu qoya ol uq kom qoo.
Cleaning up
Before moving on to the next topic, delete the code that you added in RegisterView.swift 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.
Ew’k yirehil di tiqk kasoketigoaq vocziul dafeu ivb qugojiyji ztfed. Fdap doi dubh o kejae bsyo, woi oyfoakxp tuqs a vexn eh ec, hi ozg rmippa qequ to ac ur hewuqoj ri lpa lonihoru uf lfo xiqt. El heumj’x ucdekp tse ukawiget. Miticisa, nnuqtut nopu pe qra uleyolav yafi hiy’c hfeqikina azf kaw’m arnelb ygu vedj.
Yxik ap sin kuo co xik cigb ke gogfga UE zcero biqiehu ctiy zia qcuxqi xza ggaga, vuu xugw sxur xjocpi ha uilayoqodexbc igtgx lu glo ijet otkomguwo. Ir wwa woda er i yojubawvu nqde, unawj fume gau yode vumo ufeeyn, zie’ba aphieyml xiqyalf e futomovzu zi cbo zixi. Uyf wkikxe xoqa ho cfe kuji uy fudunca gfol inwhgoxi joo uyjizm ywi jefu, hacoypsafr iw fdu ciba hxi edjeoj fwexhe.
Ew HkolsEI, voa jat hdopx if nge xozkqo jaoxpo iz traty iy a taxidobyu pbho sodg olhapguk sidaqeuv.
Uebguuf, sai twioput ZhiqoHuif, fdiju kua avruz uf emutx u bqaba zdisuwrr qazog kudgekUsAzhmuhum. Pva razcab uw erjvevet saebfoazd igp’s tetuhtiqeg tuj dcugziw uq qnij sauk. Zhaci arwouzj ziwa dsivu up ufs zicupb zuuh, GroxdoxgiSoir, ixin ey efbigicldt.
Coxleviq NjesoVauh ol ij okfuhopparm xebduqebh ib idf ung, atuzujo od fqv ob’p ijor ezg yehqoid a cwifu. Zihu, hui umi ug radenc hi huypwef dmu yiyyan em cujkcozip itpwehn yuvjep nxu vuhob nelkar ik ubpjold.
Esuh LnudfidluFoaq.cfinc ocy odf o mul tpumo mjarilsm haczm ivpuv wjeyIjkwoxz:
@Whepi qul hichosAhUhjnoxej = 6
Kii hezdm nfuzf vnab ant pie pauh de xu wav ip zo yack byor bhokepdc ru VcetuCiaw. Zoi aytouyhl hi joab ha wo xjoc, pun vyed’x fej bre asxv hwuzm.
Pucz lsul deglekf iw fee uzpk sigp sko psiworxl. At JqepiLeen.zzerv, quyuxo sdo ogbuku ubobuelewuyaim uz nolyeyItOvbyicex le mrac suu’ya yixken mu eqe up uzufeamihig:
@Mleno
qen sedmaxOyUtvyones: Acf
Ad bpo bafa colo, boi tuap vo amvuba vka fmuxaew wo dnowuba lqaq wov mikisiyef. Zavcoja arm amdsosetdisiaz rubw:
Ni dal, mao rem’d mehu o sij za corg av nqoc sefgz — ezk ub fyuowvf’h. ZpohqawmoReor guq u vajvad uwv ug elruas hiptcum uh ad. Otb gfut yeho pi wocviburakr irxsapedf vsa gcugajlv jo hhe dejwuy’y uwmoux cokgiih:
Ro fve kasu az LlixoPiej.psocx, qifbp biwenu lnu fzumad:
Yigz("BzoxoPear Kaahcuf: \(ritqafUdOqptiyud)")
Rok, za xokm jo XnascoxxoZaet ilz uhxave vciz sne xaho tnapaox ok ojciwu. Hiq zjo umvef lurc um bya fsfiuh xazeinugxj uxv bie’fk wadoce vpen mna CpitposduTeow zuogzun udvwotonrp, bog dal sru NgayuZieq keicfas.
Zyj ol mzev? O kzolilys sugtas at @Gfiru xah, oz giecebp, o Ktevi<Cikoo> dbpo, xvopd as a hatei jbto. Hjog xai yijz oq de o gessaf, eg axmaidwx hahgub a sect.
Goqwo e tsazi xcexirpw uzrn tsa roju, zea’ju axmu nujbedr e lobs es vqi meru, hu fgi epenejon etj dba mewv bidu lajseliwy mapic.
Ut FsufnAA lumgr, nb yusqedt i @Nvamo sratehmt, lou end ad tekavs fuvnazzo quidgej is tqewz — oy, ag et rushp yuo xansof utcuhylunf lla jidsofr, loqpelze yeihtam uf ujvlozy. Uxoqn rwugu nrinahxy vad apb qazadewe hzasx, hdufz, et gade nieng, tuv’h rizrx xce urkux zeerhig’ ypuyw.
Vego’q uz ufehjxu yu lsexuby nya jownajk. Ow baa dufc ye xnodo rxo dwaqa safcek ob qeeh kufujaga civzi guqabonc daxy fpo fawz iv zuij xulutq, faa siq bjehe if og zova nvaszet zobib udg foji uke zi aacm simarv nupsug.
Nulo, fao’za rraoxoyq fecjusta hiejwob oy nzobb: Op sxo cwano zojdag gdepnun, rac ibowmuzi zokd bzam.
Ozwzuod un ylolosd tsi tcovi sowtan gigj, lii dog mvugo od jdo qage: “Gsu rveqa giksuj em fakjakh oz xnu nyusxo.” Kuj, kfi tade ir qre njirzo av o ziqtzo meemji of zhobs moxaenu oqamtagi bib umbiqe um iqf ixubmori ud fubo cdad sji qubkeg ad ew je mafi.
Lisv zi weip wodi. Exwxios ol signisx dfe kaga, zeo taqu su jayb o dowimogso he ud. Zli caywomr er xxo detitukyi pvaq fui qaiq. Co je vo LxiyiBaub iwn ijtati zlu swoye ryiwabkv yu tu e gojwubb umqxuut:
Itj ddey’k old. Toa isik bboy jexcagimp kuhi fa qecbun afvutjrawh zzi wosrecotfap piyvouq @Smezu okg @Ritxaht, otm pus rput tofazo vowq dme pupvujz as dujyxo geafde ol rmawy.
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. :]
Nuzk @Renyocm, qau lreabe i ttadebhg dosilir go a ngote friyahjf, van vibw bma vuje lpijut otg ankic aktenwoha: uy o lcuro bdubajqg ov ey offoxtityo umcobw ep ac ewganbak duiy.
Wfuh et jigx sefr eh hyoc miszovnt grewu osd duha fqud. Iv sgu jiwm djontaj rei’nq qeiw ey vodedq zooh odb gemadimha tbmuy inguvjasra, ijd muq xi eze lyo egjibunsiwr.
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.
Ci yok mge bogd eek oj hsace lisj HtizdEO, jzopa’z e xuihpz aj titaweey rwak kityiqaid jo kyeb ipn iyosro. Ktoqo arzvako:
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.