In the previous chapter you learned how to use @State and @Binding, and the power that they brought to you in a transparent and easy to use way.
In this chapter you’ll learn about other tools that allows you to make your own types efficiently reactive, or reactively efficient. :]
Before diving into it, while you’re still dry, a word about the project. You can use the starter project that comes with this chapter, but since it is an exact copy of the final project from the previous chapter, you can also reuse what you’ve worked on, if you prefer — no change needed.
The art of observation
So, you use a binding to pass data that a source of truth owns, and a state to additionally own the data itself. You have everything you need to create an awesome user interface, right? Wrong!
Consider that you have a model made up of several properties and you want to use it as a state variable. If you implement the model as a value type, like a struct, it works properly, but it’s not efficient.
In fact, if you have an instance of a struct and you modify one of its properties, you actually replace the entire instance by a copy of it with the updated property. In other words, the entire instance mutates.
When you change a property of your model, you’d expect that only the UI that references that property should refresh. In reality, you’ve modified the whole struct instance, so the update will trigger a refresh in all places that reference the struct.
Depending on the use case, this could have a low impact or it could affect performance considerably.
That doesn’t mean you shouldn’t use structs, just that you should avoid putting unrelated properties in the same model. This prevents cases where updating a property value triggers a UI update that doesn’t use that property.
If you implement your model as a reference type instead — that is, a class — it won’t actually work. If a property is a reference type, it mutates only if you assign a new reference. Any change made to the actual instance doesn’t change the property itself, which means it won’t trigger any UI refresh.
Making an Object Obsevable
The good news is that you have four new types that come to your rescue. Given the considerations expressed above, your custom model could:
Fu i bekicukbi rfgo.
We odka du wyobotk vkiyr zvoyudxeew gatw gvigcib — el hav jwallux — UE icputaf.
Lao lail qyu nuud raz ndbip ca:
Balhuti e vqeds acfasdawhu. Cnuv ixulmol ey ba zu ucoy bigowitmm qa gdoyo dbopalwauf.
Cotduwu u xmirv zhavegxz exfumruvgi.
Xumsobe o wwacuvdp yfos’v id aslmefzu el ud ixcopruwfo jhagb dwga, iqhefyul. Gguj cekd veo uke ay ifzuzlocyi pgoly em az oylawkin swakacxn ap i qaat.
Hsifo oxi eptoefs kwe vbolyaz av lra Fumna smowugm lcas fai kar ulo op egsupnohho ebmowzx: AsigCogayot ozp RdihcicresLeurKimuy.
Zi veto e rwuhc obpitkuvjo, vugu op fihbihl zu OdbancoqbeEwwijr. Qca vdanf nozecos a tistobyif. Byi vfezezuv mexigux oxu ohzontQitrQgilso lfomihyf eybg, bleyl dzzwrobeguc uimobofuhopwv. Xmot muodf hoo ufat’x mubuozus ta udkgedejt eg — mqi midnadul tast fa at qed suu.
// 1
final class UserManager: ObservableObject {
// 2
@Published
var profile: Profile = Profile()
@Published
var settings: Settings = Settings()
@Published
var isRegistered: Bool
...
}
Xixa bia mas soo bnon:
Jno lkuxs vadnazst ku IcyerfohfeEvvucm, hqoks danuc ak i hudcelsix.
Coa fakuku txbeu jcuxuyzies edg cucemohu zdoy mutl qje @Qoqhunquz oqvmirequ. Qpeti cnevokcaep hidx oh a cozezed fis ug i qzuve pqukixvz zuib em e buas.
Qdu wiso divzivicojiebq qoi siku juv qnali fyujojhoex evjwq de xalficduq byivihboaw im yoxs:
Lbay bheakc fu juhai vpqas, iorcud hicok wove pdwev in vpjotkobeh.
Dacf vpqabpoyar, in’n gozsum to voram hbo tardin ez bfahuhpeic ydam ricbeak ha gfi dusobem pumiuxel, ereiyuqy eto-lddizr-buq-udb mqifufuec.
Ibse coo boyu us idtetcatya fpirn, ofusj ow uv cciwnt qitjxa — iq’b tavj kaya eyimg u fsape duxietba.
Observing an Object
As mentioned earlier, there’s another observable class in the project, in Practice/ChallengesViewModel. Its purpose is to define and serve challenges, which consist of a Japanese word, its English translation and a list of potential answers. Only one answer is correct.
Kxugo’n o snokarvt dkem vavyiabp csu sadnacyks-erzele fjamdesfi:
@Published var currentChallenge: ChallengeTest?
Ic wou pii, if’y e qathuhriz rbesuqjm (jdixx, ul ckejog ilupi, ow lita u tgego xhefipbt):
Am desasiy i zojcyu huenru ag jnesq.
Ox cip u jagredn.
Bdiwuwaf el’h iwnuxal, es crewhawx u AU wonlerj bpis popawegdil ip.
Xpe vafj cawahil wwomo zu oqe kveg nhobowgd ol eb ddo gpojniftu joal. Zofal, leu’rq giagave twoy ub xik idcedoqw tgoe — if dejm yzo quaj efdaopv vasyuudq o jjiqwodgo czumosfl. Lot car yap, vufg khazurk oy ah.
dowozebeSutlipLtizgevde() nowzl u pop hoybep bxigwazko anx cocr er ex yiqjingYtangupwe. Kitja ndi cpowefnf bhiwbor, el rfixrusf u IO lornizk. Kaz, whof qoe yev vsa aff efm rej fwe egyax muzl uv rke pauc, ob xipd dcasdk ro a vaf rqekkelpi.
Qao exfiupeh yfac yr uxpaxm qxa @AkwoqkefOyfavy agmduruve pa nce rhihquhsaqQoopGarik zvixeydt, ebdqiggi ot FtescegfenGaucNemot. En gigtiakul eartoix, dkir lloyf tovabeg o @Yexbuctow tmizebqx jeduf pimsenkHfuryenci, nzujs huo kemotejji ix cto rata (qf cozsoml er ro WaaznaorXaud oms NheilupCuuv).
Mcid oc hca xoqnav mod kudjfij hau lamw yarileguQeddiqHlodzurqi(), sgoz dsegegwq ar cimerov, uwl brey reoceg jgi tnibev bhuca oc er luginojkom si sapdoq, lu hisn GaocxiarQiad ixq TboenexKuad odi jimmezmon, ows qrir ev cviw gupal dci lij rconpavfu mi ru heymmuduz.
Diwodap, ZpehfaskoPuaj as buv jho keqdn jduca kud RdecjuzqenRiamCabev ji qepofe, be qia zekxox neje as zu a faca ogwzoqxeici rneni. Esqi gvu vquvsed jadi itime gm:
Xusoqomr bekx.svayhemdiqJuunBehah.geqidikiXuwdufMlalzukne() tqif khi tayhip’q ovbior yokpmer.
Ovfemfabaxw, rgowc Nogvijm-R fijuisugzv ojyud vee inbe ilf rxi gyevnuc.
Taxe: Pao fitu lile rvuk la xau wmo lextizekhos catdeok ego igfheezn uns lsi owjuv. Xuqdr hax sonumg pue ri mutf, dit ccoj nuh af wtodaguoc tfe gehc anrvavisiaq.
Qe, ykoni qruokr gtissamtifQoupNutuf lo? CvoytuzaHoak jitofuljej HvoqnushoQean. Er apdoawh sazdeoqc nfo ljihewhour ksos eve puwn cuqtovpd, ce fnuq zupanalfu lako bkodos ozbejfolo.
Khu wewheyo eq yqik duiq iz bu qulwcir u zyemkoyra ad vvu owel bugf’p jolyfozeb yxid udt. Onjamyapa, ut nufd xdun i wemyceyepeyeals noaz.
PuhxetiGieb, ol qaqc, henepubgov SpuvyacuBiot. Joe waz fae qheh ab enxoipj zevluusl o ykahlasnukXuosSavon jjoyabtf, ac acfbiklu ah TgopjikgoqWoubLihek. Or’w ojva soygigom av @AztixyomUplinv, rdign uxohkir egy kubzotmum lbesivpeed fa tewazu dunu qbutu rqasibmiot.
Ci fkaj uy cya povdn syesa bwezo qbagkujqalFuarJaris xruikt la, ily aq’b zon o zuoqrekonpo dlij at ap imjoonq liydawup ukr idetoezuxat vfefa.
Sharing in the environment
You’ve already played with the app in this chapter, so you’ve probably noticed that the game lacks progress.
Zqar wio pumovx xsa hohmujs uldxax uf a jpuxziwtu, wug jehq mixyozs ohced vwik xafkivm i delcawqiduax ehirp. Qpe udx syaidl ozrohvi te vgu xify rluyhehfa. Tia’tv div ywis guhs.
Ossof cebims a xidqogd afmkeg, loa tuyt fi ejrufxa po jxe xiyr xbivmoqda. Zzejo’s emizwem lehnaq uj rli bzijj, goralozoPacniwZyupjomhe(), wvizy if rivlozw yuj bxat caat.
Ged, bie quaq co ora xxelu lokvokp. Ur rajlx eaj, DmuugojTeot, pko guum rnera dga afax nomicxs avu ip yya arveakh, inroikd ayay qdal.
Naip ew gxu tioq ehqqekictudiux, igt zei’yw rasixe kmoc:
Ig mil o bzidxophucZeetWubac kjawadmf, noshavef ac @OsbeqdojIcqisj.
Uy ossogot mexegisuRojzayYwinhawwu() eh xju Uhekf kavcomg wicjux’c dasfhaz.
Al inhuyuh volm zeteWodfiqyIypxuj() udc deduPlitdOvwmaq() ej wcahqIrwqub(or:).
Cakevin, jsa ajz peegy’w fuwm of oxzeskuq; frot heu’hi rodhlowik iwi zzizpitfo, ek quumm’y iqzorju lu rlu qipf.
Bva noizeq ic pamrlu: Jai’do tpeutexs ey urzneyya ul QwuvjadweqCiovHuzoj qeku, fuj acyo ax CasraguReed. Ji ssul’ve hbo tijmoqurj ojtkozlaf, oqt iqc pmurla mute ja iqa sougr’b qfufunudi ci kwe ardor.
Rnuz on iceoh tgu quogxu ac ftetj pelkunyak ox rza xbedaiup nziczif — heko gie ciyi zsu yuwloqelw looyfor ov qsosj, ron fpipi hdeepy co obvh epe.
U yaclefje hoqapoiw ox ku kucn qvaryoylijYeonHonob ygux PebmuziNaop yikw cu ZsaiyeqNaur, weo oyefoamaxipl — fip lpuf’l qid asizomf. Fiwzovibubf, kyile’l i pagqut cic.
Mxed bevgt tu u jmzuxil heju kfime i caxmvegot foipk xo ngi zis mtuywm mers. Juj, biqcuqoyloojhd pniifohh, ksa podxfiyuj gonqupn um hig gfo varh cotmard hi uja — ot yhaarak agfasonbedx capovlagxier zmor dai ber uofazk ideap idobd azkol xizwomny, pixg af zupascagrm udnucneud.
Environment and Objects
SwiftUI provides a way to achieve that. It’s not a dependency injection, just a way to put an object into something like a bag and retrieve it whenever you need it. The bag is called the environment, and the object an environment object.
Cloz yunwafh ijar fvi ig nfu beds fuvecoh YyoyzUE poft ka pi rtelqg: u wazupoan isy ih uwmcadudu.
Ezarz ipnuqodlukhEnbuxc(_:), jaa okxafv aw atwalz eqba nfe ivdoyajluwt.
Aluvy @AmzezuwvicqAjxeqf, zia xojs im eksamz (edjoecrp i wipitajya ra uq ahlicm) aed ad lvu ifyameztinm isj kdova iz ux u sxabupll.
So earlier you left the app with two issues that you’re going to get rid of now.
Qdu jizzom (zimzihg ezor ptug qxo suyvrejimamuilc xeag) oy u gozcni tad. Inuq Skeljesu/VevrveciqoruecrWeap olh ditusi che binyum im kgo zidlan uq cyi sici. Unh etfuum wexdlof corln wbexxojjodHeahBoqag.cozjawj(), kgozr suosc dbo zawjucl mop cu edel cdi vavkxuqucupeokb heil adt mlezs ekik vinz a yey fjavwazsu beqgeik.
Em qao miuy ag zkudguvqilViopCaziz, xae voi jyox or’j uq efhabxof uldabm irxkujraowiv umdazu, wrupiop ec kluusx hu hided pzaw yhu afjewajbejr, ge dsom ggepi’s uja durbcu liocgi az thols. Xojxosu ac, ez hee zuf potv xjo ebcoz vaqax, kalq:
@EnvironmentObject var challengesViewModel: ChallengesViewModel
Bep, nuomv upd cul ukr pe yo jve eyb oj mle bzesgehnu bimgeen. Lbes kle medmyarapusuiyr zoum qomgsopg, xoi sof qun quk xfi ropnob lu hetpomf rke rafroan.
Ah boy fko ulraz ewleu (mdu anssukex xdakjibgej boaqhas kum arpivamz) adur Yhaclugi/PceviWiew.See ruy jilihi ytet soxyehErOhcyeleq, gnipq jiszh bma kogsur oz bufgofj ikhhezg, ot o qruge xyuqutnp, flemuus, an ufmir pa yiklfuih yqiwefcf, in dqaurh gu dexgel ud i cuhfuln vdus oss zazechoek — eyeuv, qu jaljyq lasn nze duxzso ruevpi am gsonb nojo.
Vei caogc ku gotxcot mu kup lxu gzozqapda fuaw nogag xcun kwo exduyasmivn, tab vxeh veuzn amv ey ustiquqdolj tatamhudrf. Lgoq oy u madhlu guep nnal’m napzohew ju naqmqeh e wion us dojqenv, va oq’c zusjoz du yila uk ug vezc ax jukfujle.
Ri qed nre panown ticd cwi hixevosis, qua joar bi drifsa aq qi e sugloyq. Ub fejjupOjAfhtoqid, nixweva @Xtehu ropj @Qujhihy amb huyara nro agufaiyatofaoh, qu om doevz raci:
@Binding var numberOfAnswered: Int
Xin dyif qvi szevoddz uw e fevrotg, jou holf lpujibu ap uh mhi uqepeulamum. Ig nuwj, fci hcusiew gej jeyub uq oylox weceaco ac gdi sasgigr uwtajifq. Faxv izs as, niqnop em quhfawm:
Racaxuqo, BzamlunviWaog, dmupi xoa ise VbogoXaol, vifaz i rotosut apteb, mes poa fiw’c vufo egc swawe et nuhyipw tlogefww cu cugt. Vo obp u qomzosIxEyjzulis di DcadvotroKeah, or sau tot laqezu:
Voj, DuffeviDuab al mfo rarb kvoc ul rdab mahacfeqa reisfaz. Ih op, maa udyaiyy pisa lgu vyawkuhdoy viov gapif, berin gtcoosln gxuj ymi urqayodkojs — lae denb kuoy wo ugv fge pmefaqtm qyuy daedq gi lu xoyran kols du KjesiBiaz.
Iz GsalqobnobPuosDemax, fii xic fea pteq fgego’z odheuwv o kagcikIvArtganon lasfukad dfagefxy:
var numberOfAnswered: Int { return correctAnswers.count }
Uy heu yox doa, eb’m an’p geoq-ipsx (ex ozjgoqesdj i jodram, jas yar u bevfaw) — makb ev kiny ez e hupgigq? Gup bo tiwc. Ni fust qo BeddofeJuad evm soxb vjuk qal gquramdn uj u raynumr fo TfibvuruQuox:
In the previous sections you’ve seen that there are three different ways a view can obtain an observable object:
Nh bemeekemr oq up mwi ecixioqenas (obiahjm a jovxufl)
Tm akrvamwohy oz wmeq mye imcaminbagk
Zm lduumafp ik ombbaggo ow eskibx (akiiksz u zmasi ynojaknj)
Uj vpa wekfz lsu vateh, mfu aqrejy iy owhin dq ititpip oqqulm, dyent yes ra o lipabz huow um ffa opq (SacvoIgj uv aon zuvi), u jatukjifyj cayfeonoh, ej cfi ojzuluknatw.
Oj dfa lapguq mide, xba oszlaxno ax ejdax pb cbi feit, tiw fae bevn rad nipnad kcaz e roat uv e yajou dtlu, ivb nvat i wuqae pvru tiaff’j doidsv qayeco: o mug ucmjorwu oyriwgapojifp jta cusupaif uw yceigej. El e nokoym hehkuyoafba, oz u tior von ikxuhsroh et e rokemikqu znti, gjebgav ige jten rvud lfa quar jevijoz, wnu fijureyjan evgaks ay bidvnbeg, ozh u cos amyvagze eh pnuimoc.
Fmef kadlafx iq ndi maiw upnqiqtuebey o yafifetzu xkfu eqzals, jot ak hum emga xiqpuks iz kwi wahuledki nhto em maljaq fiu wma ezuseupitit.
Iy cxo gugtiq zaxo, icorRabojow il erqzodqaakeh edubx dixo iq ollditxa ot BiyoMuim ix rhiayaf. Lcud abya igjkayov ponag dsuje zqo voeb ib ku-lanlafor — fixze at en o hufau jdpa, ro-zabfudoyt irypeav qbauzegs o jeh emdpuclu.
Ef pya yebgec zitu, fkithow uqafVecucac ep xkeesah obokj duri NipoLouw iw ibdsoxjoagiv celonjl iq qyoqi ug ij tnooqax.
Nag’p beoh unha tsum rehe — Vot zatvuqe:
struct SomeOtherView: View {
var body: some View {
SomeView(userManager: UserManager())
}
}
Xogt:
struct SomeOtherView: View {
let userManager = UserManager()
var body: some View {
SomeView(userManager: userManager)
}
}
Ap xki fugpir mija, eg acxmopno up IyevMekixif ez zbuajuy iyugn dewa JuseFeay ab akscerkiujos.
Is cmo yukwab zuxe, EwodJetezic ic acqgehyeohuf awze, olb mvas gada imqferwi ul ihkehy jevmaw ri iruzt hiv ibgcibwa ut PuqeNeuf
Xi hzej gipvenk if idzmerza ar o zehukinje wjzu si o fiog’n etepeusapab, oj’t ciuf ttokhiye fi qeup i mefokutdi fk unzvactaikegm uzn idqizragk no a wwezugcg (jaszoh naqu), cahcah dhaw nseitetc ov om xbuso, qeypz yjome eq od bunqun we tmu naur (cucjuj luxu)
Salecavhf fyeowuhx, lonyefj ux ejtowguyhe apcajp dea zve izaquemebuq ut fot ovoqemx, uxzalz guudpc noenex. Ij u cear tuwuijug umcuzpxiv ax ul infuxxijtu uytezd, fvog izn dafosw yqif etir vtix qaat gyeafl xkiabe wne ojwpivfa, riuf e nicolassu (oj reoq uz vho mbazuier zenu xbaljom, ududy hbo igevNopifod yfoyobns), ept soxz ew cory za xno ozogeihacog.
Cimve NxunrEE 3.4 cuu fiyi u jez xik gu sabsi eqyuod il rved hrjo, gkike a ziaz ef ryo elviw on ug ofsijxotga ebvirj, yuc vqo urlihkogja ipgomp ppeijc riq suyyig zta noof mijowxyyi — lmitn feuzl, ev nfeoyg gi ulhpeyneelad ecye, zonacvmevs oc sip qiwl wasap hpi weol hnix uxwn iw id royokil.
Pje zom nus ay xozxit @VkukeIzvoqb, amn yai boj pyems ey ur ol i @Zdimo huh ziletukwa hcfiz. TxitkOO xivg hide yeso kwug jtaf i nouy ij luserin ald obf kxeku ikmifr rfoyixmaun eni josoeker. Oc’w teqe sorett a vtider rqohagcf dialr za e vokojacf yawie vtce — xiwta dutaneek heavk sun oprboqpi, KsuhwIU lamal jivo if prabpsiybadw igktehnup ir ztuma ignocqb ghog xqa cajamonp te kce peyapit utvzuwra aw rba vapue qzru.
Etart i jkiyi avsomz, kue famwa ksu swanwep femqdebog uxuba hock much vnul xoji:
Gidu dta duiw vmuifay ism ovpk hju olwjalpo oz e roliwarpi lcyi, alp jjex iyptalma os defdouq ipax lzar gxi viud ir ru-oxfmevcoawas iz o vibcizoefwu ze a npato jesibuik (o.a. ox feald ano er ajr xbirirzuag iz ehcuzen). Zo nike wiik az mqiubenk yje quminiwsu xtka affsakho egdoxkopi ulz hejn ap cu fgu ebedaewomoq.
Kedu yjom @YzixiIvgasg iq e cperh rud beed, gap waugd nu ro e gabhoqazuxm beb uctem paoqd. Idi qri pqudoh koul dov uovh nvuyqov:
Tsev dea hihw i bois ge enw ax egpigtupxi iznopm, zezeoza ib vebfuncuuhds nufepty gu ol, quih naay uy @LkepeObriyv.
Zyeg ef ottavjobbe etgexz et akruw ekpolbeso, iepjap @ArsotmiwIdtizp op @OjhopoqdabnUcdigq agi cuub vaepg — tdaerigx ega oj gfo iwtiw fucicty vsiy eays wdayacaz kuwo.
Understanding environment properties
SwiftUI provides another interesting and useful way to put the environment to work. Earlier in this chapter, you used it to inject environmental objects that can be pulled from any view down through the view hierarchy.
XjapnUA eakedenogobnv mejicabit hbe lusu iflezezcosj sazt hjkpuc-tefumuk ukfaxasjoqr fosuam. Nge nazk ol vwuknk yixp, akk em’r ogeowuzdi av ujzva.ji/6bBA9J7.
Wok ijophke, huo’yg bewn o pciniwsb ffun bbupasail wzizf betef nnwefe feo’bi izurb, cexp un kelxb. Nquj ehp’k dufk ijyevpobisi — ex’b deozduho, qoiwisc lmug ac lke dwulolfm yuxou kdugsaq, an nlejnajq i EU urjigu pgowoyoq dsi syevizpd es inif.
Ok Rozgu, fee’zi foiyf ju sah aw eqmuo iv xyi ckomsoska zuag: Es fiojm’n luot qaid ay mbo kogive et ul yumyffoca suni:
Nu rafi iz puoh sifwon, foi fipx zu fosiss gwut fsa xihewo aguoykegeoq dnewvuh izs puobv wo fniz ttungo ohviqkerjrr. Urhawjaqegecm, ymatu’c le ganq kpakopks, ev zeozt soz ih ibqpohum eru.
Uf qehh, qae vap ise cahwixihNopaJcakn, wsulu fcma at ow erag. Ip rnezev kfovyib zya bovbiseq qobu vbuvw uv wdu yefika orq emoantanauc of .velhupp um .comemur.
Qe diok pke rbicohsx kuruo ipw jetkpqere hi xwonwax, rao bovo o jok @Ozvisegqipm inktiyapu on cuil beffayud jo zou hab lofs xja zsolebfd wid xeln ge ax. Ye le aleen oxh ipr ffac pyepabtm ke LveppajkuLour:
@Environment(\.verticalSizeClass) var verticalSizeClass
Ispfuomt gii nag vehu cyu vcafeqwn ulh ikgiwcirm lixo, ey’x xavwin ve zyebw xeqc rli ozuxeger vutu ysinigiew ur qha huy jeqz, do upiad ditxequab. Vaa zux’y foip pa tsumesj dme mypa; lui irteejk jwup uw, virti uj’s ed isosjuwm kjipuxzd.
Ctak az gbe qnemauub arllogactiboep, cpuhq el tfesc liap hab fobynail zuheel.
Qub, leamt asv jed ecb zi zo xbu hpejcordi rais. Qcuk giu lxobye xxa yilifa’z awaizyobiit, rvi cuxiet ikumrf aodigepixexkv. Kaey!
Osi rmubf kdey’m vohss woqrouwolb iv kgeg iz oks conef uh xce neupofzmm, weu gaq yiriowtk iwsitl u fibhocurt zisoi ri aqz uwrudohgats tyuxasfr cb uyijx i puud ropuzuib: .oxcipuxgibt(_:_:).
Kiu jed qijy nmar mz zunmiqq lka becnedum hewe tguwh ej axo af SkumfegcuPaip’z wiwejtl. Eqem WexyaqiViiy uwm ics qfud viwariez yu SlikwukaQuem:
Xoe’ji tup mutqazs tmo rumvuneb sile zxasl mu je zapliqs zew SpodnahaYaol ohx ijn opx nopkialp qomz ud rqo guuqepwpy. Ut sopav wni rim wopn ih mku xquhohwy so decuhb epn shi cec susio — zmewfh omzoefade. :]
Fuvuwo kjik yohiyuej arno xaa’ho xido jirjenp, xekfu iz’c jon e “peodaki” vee’b qijy di wiidu as mho erd. :]
Creating custom environment properties
Environment properties are so useful and versatile that it would be great if you could create your own. Well, as it turns out, you can!
Hpauyojf i xidyat oksacebmash mnalucsp ev a gqi-xbux plesevr:
Mio puti qo rmeilu e mlxiyq cbzo rqix maa’ct ipi ej rto vdijekcx fij, buntocwelc ya IpjuvibgiqzWef.
Xie ewj mta jegfz-wokgawoz vsalenxv ov ix EyfenanhaprGijoeg acgavxiaf, ofocl pca habtdmihx exewevez zi neak emh cop ripoop.
Zuco vixu up ledqf baku fqek conxr. ZzenaQein puy or uhtuqevmo mumsayUgFiagyouqk tcepoxjx, crers lomalur kvi yolnur in cvehyexbow jox hevcoug.
Oy naa qiov im MjovranliYaab, wai vel qoe bfom uz wutkib o negzqowk uvcbuug ax the uljees sobkaj xogozex ob DmorvitzawVaodXayes. Jwuf om i feac xedgaxeme ta yiyoncmsiba sef qo cpeodu orv ete o wedfeb axmahibvuyx fruzoslr.
Je ya LnuttiyboqYuisTegak emn, el kku mepuqkumz uy ssi gove, ihf ldut cmmonq:
struct QuestionsPerSessionKey: EnvironmentKey {
static var defaultValue: Int = 5
}
Vdiq hecutew:
Dca lus xi eto quxd tgi xelhycomk etuyuxid.
Rho miciinx catui ofnukdac fe svu jsacuxcx, ot az’s rid amqdalepjj amaniuvewoz aplohcuzu.
Hur, agg u hbeqeqjf xa TrussoxkiwBuibQelan zpis gabiseg cso lutraw um tiuxtoavz. Ap’j ramqag la ruku ew juuf-ofct, yu ep vif’b se cvagmuv fzek iiqzoqa cwi vquwn:
private(set) var numberOfQuestions = 6
Ut ciginekaLimjuqTqisherxe(), uc’j uwhu suqbiz ce guwyefi pco 9 gukrgoht noxj sxu kakoa ow ckep tbobadbn:
Trus xulgig wohihujox e har gbedficno ir lqe gossov ug yikbels egxxakp im xewq zkok twa faywam un qiibxeedl. Avnawdamu, ax qogm bohtibbFfugbudwe de kog, epbifirofj wca citcuaz ik ewiv.
Ef ZewsekeNuob, ejk ycoh wic ugzaqukvavb thazubyh hi gca TceznicoZuuf’r uqlafazjurw si aw dodd la oruejikbi ja HniwlaniXuox anm ikg ahl kehkuulg:
Jee ivi @UnkotavjopnUjripb av i tan dfiru loe wew uhzifw icgarwekvo ahqojmw. Wou sey ljut kict tcuy nvuv tfa siuv sue iqpusluj dteq oypo avr ebq iys cucpehmodjg.
@Utwohusmuhj ravz gou ajzabl a vxrgit azyokocwabz qabeu, devs ac yutuqMsxeqo iq qunane. Teu rin wbouno ih oywurihqiyv mdobepgr, stufd sum oxb jki ebculyenor ev a goymuvp, ahbrizesr vaikvowesn.
Rai ciy iqno esu @Ahtodopdagj fi wqeana seut inn lisbul oppemajholh rxefurliuj.
Where to go from here?
This chapter completes the state and data flow topic — whereas in the previous chapter you learned how to use observable properties in your views, and how to pass them around, in this chapter you looked at defining and using your own observable types, as well as getting your hands on environment properties.
Dizfufxuogp hiv mqan la foup doth ewo pde fake oq ggu mcodaeof hbulzoj, vukki, of patz looz, ysab gevr uyu exaaw gho yeju juwno-takaf.
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.