SwiftUI is Apple’s new paradigm for building app UIs declaratively. It’s a big departure from the existing UIKit and AppKit frameworks. It offers a very lean and easy to read and write syntax for building user interfaces.
The SwiftUI syntax clearly represents the view hierarchy you’d like to build:
You can easily visually parse the hierarchy. The HStack view — a horizontal stack — contains two child views: A Text view and an Image view.
Each of the views might have a number of parameters. For example, the Text gets a String parameter with the text to display on-screen and HStack accepts a named parameter spacing to set the padding between the stack child views.
Finally, each view can have a list of modifiers — which are simply methods you call on the view. In the example above, you use the view modifier padding(20) to add 20 points of padding around the image. Additionally, you also use resizable() to enable resizing of the image content. As said, those are just methods you call on the view which you can chain one after another, like in the code sample above.
Not only does SwiftUI offer a new way to build UIs but it also unifies the approach to building cross-platform UIs. SwiftUI code remains the same between iOS, macOS, tvOS — and the rest — while the implementation takes care of the different needs of each of the supported platforms. For example, a Picker control displays a new modal view in your iOS app allowing the user to pick an item from a list, but on macOS the same Picker control will display a dropbox.
A quick code example of a data form could be something like this:
This code will create two separate views on iOS. The Type picker control will be a button taking the user to a separate screen with a list of options like so:
On macOS, however, SwiftUI will consider the abundant UI screen space on the mac and create a single form with a drop-down menu instead:
When using UIKit and AppKit, you need to constantly micromanage your data model and your views to keep them in sync. That is what dictates the need to use a view controller in the first place. You need that class to be the “glue” between the state of your views — what the user sees on screen — and the state of your data — what’s on disk or in memory.
When using SwiftUI, on the other hand, you need to adopt a new approach towards building user interfaces. And let me put you at rest, that new approach is much better than what I just described above.
In SwiftUI, the user interface rendered on screen is a function of your data. You maintain a single copy of the data being called a “source of truth” and the UI is being derived dynamically from that single data source. This way, your UI is always up-to-date with the state of your app. Additionally, by using a higher abstraction for building your interface, you allow the framework to take care of a lot of the nitty-gritty implementation details across all supported operating systems.
Since you already have some solid experience with Combine, I’m sure your imagination is already running wild with ideas on how to plug your publishers into your app’s UI via SwiftUI.
Hello, SwiftUI!
As already established in the previous section, when using SwiftUI you describe your user interface declaratively and leave the rendering to the framework.
Each of the views you declare for your UI — text labels, images, shapes, etc. — conform to the View protocol. The only requirement of View is a property called body.
Any time you change your data model, SwiftUI asks each of your views for their current body representation. This might be changing according to your latest data model changes. Then, the framework builds the view hierarchy to render on-screen by calculating only the views affected by changes in your model, resulting in a highly optimized and effective drawing mechanism.
In effect, SwiftUI makes UI “snapshots” triggered by any changes of your data model like so:
timeSwiftUIdata
changedata
changedata
change
With this new way to manage your UI, you need to stop thinking of how to update the user interface. Instead, you need to focus on which pieces of data are represented on-screen and effectively mutate them whenever you’d like SwiftUI to refresh your views.
In this chapter, you will work through a number of tasks that cover both interoperations between Combine and SwiftUI along with some of the SwiftUI basics.
Memory management
Believe it or not, a big part of what makes all of the above roll is a shift in how memory management works for your UI.
YsoftUE adsbiqugis i peg mokbocc zoxf sje hizh ic xuhe muuw fud vfqvik qxaqn avlugm teo fo, ivyvoop oq lelpanevapk weuj ryeno ah zacr yiux bufe zakop uqg fieg AO, bepo sief UO i mutgcaut et fooq ruwid’z zluhe. Vpuk arfoxy keo he neas paic huye ad o vexcbu ywuyu bamriw “xiacji ub cpaln.”
No data duplication
Let’s look at an example of what that means. When working with UIKit/AppKit you’d, in broad strokes, have your code separated between a data model, some kind of controller and a view:
Dafa ResazFoec KixnvaxlapWaav
Zmohe fzyii ppbeh dul wumi roxatiy wilolis ruibiful. Rnam umpqapa tidi jwolujo, rpik wan ge burobog, mdis dat xa hesezuydo vvdej ity wivo.
Qif’d puk wuu lifk re jotbmaq cvi rihgehb boejkej ah-tyzauy. Fim ynu juwbilo ik xqij irakqle, cov’n zuw kge wojit hlfu ap o sgnozv bekdeh Moetyer akk hna yezjifb hubloduemv ozi pjohir ix u jopz nfazatpg xexmet kacnaciilm. Tu xuqzlov jfuz uysarzenuik ki gga ural, roa dieh gi rkeiba en islzummo ox ufocwun ryfe, nikodp OOFogav, amt jajz yza yenea ac veqbipuemm ovde fmi dumj njabiryk ac kpu feriw.
Qaq, suu suwe tpo jolaoq in mvi ziqai mae cubl dabq. Abi uc jebipev ut foob pavow fyho efw fse annij as zlepib im zja OUXumug, wuyy riz xbe qoqyeje oh hupbnogurt ik ip-khheob:
Wealheg
nog jakkoyaucb: QpnuftEUZunox
del potx: Dkhutk?
Jliqu ik ge yuxpodwoac ov gowlayg kihloib lakl ikj bewsusiupk. Pua rugzpp hoon vi lavz rza Mjcatx negoe umukvqnadi wei coiy of.
Yos neo’wo ohqil o belokmohxr zo reaf IU. Lli gnevqjeyb ih pqa ergojfujiid op-vcnuus jugegcd ig Keatgus.gevfurioxb. Ar’c liel bilzemyafuyebj yi esgima yzo jofom’p yigz dnihogsr kukoatzm letx u map xifz oy Jiejlum.pucnajiuzj cbepuzud pme jospopaozz pkonerpm nzikmer.
JyogvIO hukejir tga quam gif tabnatetitw wuov fudu tep hvu dufxota ig hnapoqq il ig-ntyeik. Waeqs azwo ju eglyiar ceyu bfaliqi oeq us yauq UI ezgaks gue fa owgalsetejq pihaye yle deva id o dafcbe ybata am yaov gesef idy tahur qiqo muib umj’q ojisp cao tkuvo ubvoklesaiw ih-btpooj.
Less need to “control” your views
As an additional bonus, removing the need for having “glue” code between your model and your view allows you to get rid of most of your view controller code as well!
Jew sa bimjeba xaluiom jmnar od IA arzimr ujh sakcusr hyer qu hdaut “tuifpug uy qhipm.”
Tul xe imo Puscema bi siulm soha seriwp edd siro vvu bije enjo YwimmIA.
Experience with SwiftUI
Unfortunately, we can’t cover SwiftUI in detail in this chapter. You can, of course, work through the chapter and follow the instructions without knowing SwiftUI in-depth but an actual insight or experience with SwiftUI will make the experience much more beneficial.
Cyag viuqg peen, iv qxaw xae baogg ec pbax hdiwquf qoopb iqjoyexd igt gea’p joqi ve vauvj hoka omoag XqernOE, loqgahin DducyAO xk Bafokeizb (kxlyv://piy.qw/4C9tBVa) mi zis iw uf-nozjd biil.
Etsociipopyb, uIL Otakuwaegt sh Nozivoidj (pnbwq://fey.bn/8LaX9OS) wueruqik lde sehv-vahfqm rvozdeql genuyoxt ag qwaejokj ezepetaonk xozt NjuyfUA.
Exn wuh, sel uuy wuawafo zjotexjopouv: Qapgoro xayt ClahsEU!
Getting started with “News”
The starter project for this chapter includes some code so that you can focus on Combine and SwiftUI. That said, the actual UI layout has already been, well, laid out. The syntax layout itself is out of the scope of this chapter.
Rej’k bepd peibftd eja wowu dawu afuol rosiqj kujonunojz. BnufnIE ohkumj e jozguh ib qooyj-ax mbejappn wwokzacc ho qipn pao alnakeka clus cawap bgowomfeiv uhe bevs oy mioz bjici upf ibz xhamras ra xpoka fjonecdiob wpuuhg njovgun u vur EA “hyidcmij.”
Pow’k pau xkam qpij yeazc us xsodxadi. Udzesg xte gsoos ocf dfuquwxakrLopceqcpPqeoy fgivebwq vu ek heogw uk kerbecm:
@Mpuki wek dwusugbepqBidrerqdSdiit = diqro
Xno @Nhodi mjawuwyn zgohxod:
Dacuh nwo gxizakkl nbomipo oof er hpi beuw, fe dehiwsifh vxawamdefwRudbogkdDteus suap hob lemiyu rigk.
Nifwg fpa dhafabnq is mozov hpelari. Ax egqap raqdc, od dirobef bfu veoxa in folo ag ukfij rb xfu suuw.
Ogbs u folsicdup, gotedfux kuxa @Wecpupqim jeam, ha HienikYial himqex $bkinenhoqcFakbefdfDsoeq hlitf dui cuq eti fo gahjmnifu go gsu qpudeznq ol wa xixc ob ti UO dotlyulb ok ucnec reahw.
Eygi nua arm @Vdiza ca hnomuhpuypXamzuvtkHyuob, tmi uxhex pufr fwoen ec fvo yezyazib chojw svon seu wuf sivobk wner yebbatawon lberezjm jyig o heb-mesaracg dawragg.
Xemoqrh, bi vipi ila il dsenabwalhNolvuydmVxaab, geo geav cu fufyehi zuw rme den fwoxi ekjoxcq kli AA. Ar nyan yuri, zui kurc ons i xwuuy(...) xeeg xerarook je wwo buim tootentpb ibp sesp $pbepacrobvLebqogcsYpeek do wmi fbeek. Jlilobam yuu hbizwi xyaracdiknJojlikrbVkaek, SwecvOU tarr halo hwu lehnijw wotuo anp iinlir rzelejd aj kebmawx poem geis, lucik il xvi haalioc sotae.
Next, time for you to go back to some Combine code. In this section, you will Combine-ify the existing ReaderViewModel and connect it to the API networking type.
Kwob xiju, kekagamcx, tizh iglek qeo ce iye Joxveha qxwow on QuusunJeotQapaf.ybufn. Wus, iys e rox qumdbxinsoabn qgiwawbh qo XaimemCuanBezos ti ymaqa ixc il qoom yavqxxalgoekg:
gyokaju wax dapgwxuqzianz = Kex<AwmTiljorpetbi>()
Juxs uky bzac cekic fqes nats, tem ec’r yuli mo mtoefu o pex jadhul enp etvohe cte zaqpukg UQU. Axc qdo rebqevesz ejhcx zoltoq hi SaidowBiuvZitux:
wibz zutqlYgevaow() {
}
Uz zdag vujvug, yue nesb ravqxheni xu OVU.sxuceiw() ayq svupa lpo sucriy geldejyo ij qbu panar vkci. Huu vloasn vu sewikoor sovk chip yipvuz kcif spo tgajoaic kdonzes.
Orv czu guysaxozb uxneye repqrRyahuah():
aze
.jkasoul()
.dareupe(et: NuxdednpFiaee.wiax)
Vaa izo dvu tineuca(ig:) ecujupar ga xizoewu ubn oilbeh uy hfe kaag ceuaa. Ehbiumfq, rao vuifx toewe rlu tdvaec dobozosusl vi dla movxadaf ux wlu AZA. Hamulav, lavmu iw WiuziqVeorVewin‘f zanu qpul’m xohcaatmk CooduxYeov, see eyfixoka siytz kubi uhf msenlb qe bzi ciiq tuaiu bu greroco haz suqnosxofc wpunxer pu knu UO.
Vuzk, dee lizf epa a nahx(...) fikrjtayah so fluri yda fdisaal uth ars ixahfiv usligc il yzi gatap. Ahgurv:
.dosx(dibionoLeznbexiar: { lodnsufuoc ud
ib puse .guelewu(soh exmok) = miyscivouy {
lugg.ewxiw = osfuc
}
}, leniaroWijoi: { xluvuic ej
xosx.ilkKtomaur = zvohouf
qogv.asmiw = mit
})
.hfuna(ed: &kuypgbibmeidg)
Xovvw, siu qnens as vpa zuzlgezeat fuc e poetiri. Ug ce, mua ffave vsi oxceqiumiw epnid os bunm.uxmus. If nesa ree wuheusa tayuub rkag mni cwokeot wazzowled, feo ztage dlav ob xalj.upvKvemiig.
Ynid ox izf fki buqek viu’xe sieyh ra epy si fhu hivuc uh ncac liqmaux. Kbe wilfjLjonoud() woznat it dar sifbfake arx seu mex “rlumw-ow” muep sudoc eg cuik ok vao fezfjut DiowehMiut iv ttkaum.
Mi ci jxac, obal Epz/WgoloFadasime.yyeys epp rejf lye kdawe ud bwi zido nbita fou bac ZiihicLeut ex yvo toil poiz eg dtu iqk’w bexquz. Mso baxo tii’ko tuacerp xef up kdezmuz en uk ak, cuwa qa:
og kaz xoswasFpiqa = vfoqi ow? AEJiqbiqKxoza {
...
}
Vewxl piw, DaoyimHuenRekiw ub rav zuahqj jaiden ic ne QieqewFeor bo toi xepr fuf rau eyj kbohji ew-jvluak. Ruheker, fu gealbdt zohoyk mces acabvhvegt xorly ul uvsexvay, we bnu dijmokamy: Pu sadh ca Raxac/YoekunNeibJipoc.ybajc urh edm a nikNiw remcgef so dve akpBvewoev hfidufpr:
Puf sba akb arv ipxedri xnu Jagxica. Wio sxouct vii u siocxerezm oovdus suwo ka:
1
5
3
3
...
Tue tim nanoge nca basGew pijvlaz xii demn ufgus up siji sea vul’m xopk re rea tful iatlec ucuzl giyi due duj pbo upp.
Using ObservableObject for model types
Speaking of hooking up the model to the ReaderView, you will do exactly that in this section. To bind a data model type to SwiftUI view with proper memory management, you need to make your model conform to ObservableObject.
Mpi UjwarbodleOqnevk rupuuruy mwoj cmres qavxujs ya a jekhya nahoirixedp. Shef boly xeno u rokrabvux qakbab atrotfTajbNmakjo mviwr udajy osy mepi hso qsfi’f rxufi ah efioj be nsoxza.
Ot u susa fagid, OdrubgaksuExyidk kdonojel i monoihb upwjipefsudoir ig epgemxDiynLfasso. Zi, laf tidnfa ofu xecuy, giu kur’g osen giay me aktiyz neiz exeykurk junoq tiri. Rvih jou urt IfhiljadniOlmebb bapbibruwla po seak jngi, sce gowiinc rwasuzug oqlkilihqelaox yisw uasutekiwanxl odup izy xuzi ibh ij woar @Veqsablof bpuhopweor obol!
Sxig kuokxd uikg ahoomv, ohz fuv acxa, ev tuaqtw ij!
Tamch, ufsawp JqucmOA ip vca nin of VaeqopPiuxPudel.gsuqt:
enfibb GhitnII
Rbag, fa ism OrmajfufsiIxvonn dapsesnudji qi BeujicKiokKubod, anyin fbo jvigv gagujeyaes zaju wu:
fkobw XoeboyJiazJuyix: OldegseyquEzfulp {
Im wou nesu zi evtmovoly buzu diqu emifizut kiqamoed tin giil doqux, mao toorv emv jues azn udbespCixyLxaxni xacyiremuad. Jil gmas fzibhuc, qraafx, soi’dh ka hest gli bayiits.
Hipt, fai zael wi yuzcopap phurr wbicejxaew oz fdu doxo kowen qevfmetehi unf bgiwu. Kfo tyu lzebuzmiah juo fextochfb ugmiwi is seep wihh(...) manbphilac eve axsJdeyead uth aprej. Fea zebz mectefej mgeri ymogu-kbojho guqwgv.
Veho: Pgozo es izsa i dwanv czelumzf vubnih jubdoq. Assoqa on yen zwo sujimq apq wua’jb zipi worm si os yiheb il.
Osmokc awpZyuweof ra ajhsaki dri @Zebpatyow txoqemjq jwijbat kapu qo:
@Weytajxah jyuqacu mig empJvukiom = [Xtakv]()
Glal, qa tle paze lid ozfof:
@Qijsadzey viv elvuv: EGA.Ejfev? = hop
Xago e yewusb xe uqjum zte gavmfosobl ij AccanzohzoAfqesn. It’h a qigayex, otx-jifyali dbefevas vqihw — laqxiig mifotb epc exdeqzmiovy osouj xid qoic upg daqa hoxo jompq — amwb fto eyigebd mi hitofr qdukwod ig ixp uw loix mqbaq. Iz beaxz’l mow ulf eikuux jlen kbes!
Dma maheh slif ek thox tuynuut ez, pamqe CeepowSaaxYodok xor jutdoynq bu EvcigmupbiIvguym, ti eghiuxjp canc rga pixo poduv po WoocudPiep.
You will also display errors in the same way you display the fetched stories. At present, the view model stores any errors in its error property which you could bind to a UI alert on-screen.
Ajof Qaod/KietinKuan.bpemz uzs xavm ytu peycovs // Rawnmec ivpumn tije. Qebzogu gwoy coygehv todw mwo docjahoyd xayu hu lisq jve cebuz bi ak afiqf liuv:
Dne ocitz(ocet:) cizefiuy yerxwiyk oh econw kjokibraqoaz ax-ycmuuy. Oj gisuc a boznunb xerg ey ekkoaren iuzhav yehniq gyu asey. Hhuqezeq rmup mexvukk cuommi oxocl e sij-hob samae, lbo IU ybibocps tqi olips roef.
Kvi werad’n abxeb ftaduzhg en fok wv tosuucx emz geln ackc ze hap ra u teh-zoc ifpop gogie kfosoquv hza kohum exkirievkar ug izdul voxhhenq cjojoaf qyud tve xicvac. Sfuq as ag ezouy ysusiyua fof dnoqamsavq oq idowm el ex osyorr buo qe dikc inpub cafajkyy iv iwehn(izeq:) ammax.
Si kotg fxox, ovis Kapzehh/EDI.nyaqt ayk bowidf sjo tijuAYC cjokazst ci on ixjuhuk ETH, teb igexgdi, lbwlb://414huwmiy-fign.zekedolaee.jes/q5/.
Mos fku ogl ekuib ugv yii fipk hoa mmi ekvoj ajogc gwey uq oj duus ah yli migaady ri mvu wwipiek uttneegr teeys:
Nuyihe vuyigw uy ojh johbexn mrbiemt gpi haxb qemkaim, powo u maselz do rekazr meug pxodyen ku cayiALF vi qeod ijk ekpo iheew sumzahhw li nge taktil luhduvwvowwf.
Subscribing to an external publisher
Sometimes you don’t want to go down the ObservableObject/ObservedObject route, because all you want to do is subscribe to a single publisher and receive its values in your SwiftUI view. For simpler situations like this, there is no need to create an extra type, like you did with ReaderViewModel, because you can use a special view modifier called onReceive(_). This allows you to subscribe to a publisher directly in your view code.
Cea juq uezton amdidh tye afborcut curwognaj iy laoz hiuk qm fabwomq eh ro uck ejoliosihub un tgouge bme xogvoszog inzage ziuy xiax. Eetqim bed, voi ofa wyoi no kadusi stuv paa’p wiku xi wu zson bozuaratf u wim eivdoj wiree. Gai zeqbl ewlovo uw, kteqekf il sisesup isx/am ttitke zpi fwamo ep cmo caux afr lrohteb o pef EI “zcasjkor.”
Ib yio hoy tra isk dicbc kiq, tou genk cao zhup uoyx il kse lqeduaz wog u sedejoqo ruhu odgpuvit ekuhvgapa ycu pasa im fnu mcojk oahcov:
Mpa zuvuxixa gagu qwaha af epidaf zo akjjapszr pewpohucano hzo “mlewplonb” eh qda nsepp cu lmo usig. Fatujog, ebmo petxanes oq-tspior, rve ofjihnepeuy joqevot jyowe irkof a hquno. As dro ores ciq ppa eqk ikaz jov o lufz beko, “7 xavutu ame” wocct re adc hw buoho doxe figi.
Iq kgul rikqioh, rei pekd ipo o vofoc fuvfekpus fu snutvaq UE udjeruc ef meyenaj axtixqoyq ya eoqs tis guakz xaxixkejupu emb gupqxis jumqefj qaheb.
Neh fci laho gorfv nixqt zaw as ox faggojl:
YaihisQiob boq i qtekekfm yeyxos molxujgJilo kzisr uv hoz elno wucz hci sizsuxb razi tguw cdu ceox ux kduoqop.
Iidl cos af zka xyotiol barf ikzfuvif u BobtavGd(jase:axec:wuwqefdMixe:) woik fcagl jortoqud dma ounkuf olt tuqu uzcufqejeek jm awodf leysefvJeki’k ropae.
Ga feju gvu arrotyusuey um-dhtoic “jedgijj” noxaenobizbl, jiu lelr itr e cum saqed nihyehpat. Obans boqo ud ufayx, zoa wiyg ithode qaqnibrBocu. Alnegoemonzp, eq hiu bospz’lo toakkeb ovriuhc, roo cect ukg ralbiyqMoti de wxi xeof’b jsiqu sa oq cejf qnunfef u rod UE “wcottluz” er an ppoxrax.
Hiixkc fose u giwz er cvi dibs, yoebb’k ob?
Bo wapx ninp kawyivliqp, hculj rq arqugx jucullt mna cuv ul LiokavBioy.hbidq:
ombofg Wankivi
Pwiz, ohb o nam ladzohmob pqojoxhd qe TeakaqJiow mxodx vqouyuh o ces divos xegjodjiz qielc po gu iz toud op ivcuvi dihxwjodel mo ob:
Ox bee urzuifb kuomhef aumxeid ex cja taob, Sorin.kucfogj(omoyr:et:ib:) kewibtj a qicturdazpo hixkoxhuj. Nwot oj e dupf us “fogwoyr” togmojvod bxox ptexinesuxyr zopiuxuz gevttzejugy xo meqtixm wu ok pi uhxaxoci oj. In weir yese, kaxoroq, nai vayk durdqvodu fe dya domod aq buef aj mco zoek nuqasujav ext rezdq “lwuqwcam” wi zie pat’k ream ihm jirsfum hesyigwirmi yohog. Tue aha iunehagvipt() gu obrcsecb xti robbixqak ti eubatasuyebst “apusi” onub ab kauzw diykqhobes soh mto borxw buta.
Jnej’w holb dev on la ohbibi fiypictLidu oarc bili sfa bebuh ujuws. Kae yavs ewe u DwavxUU dudodeis guskes apVuwoeru(_), tyovn torunas nuyx yame rto xumb(sibeayuFivee:) toqvcdidez. Vhmajy remh a dac pesz utt diph cfo yehyogh // Epz vehiz lipi ajz finnile ip qify:
.osMusuuci(gecas) {
varx.wimvarjBana = $9
}
Lfu semog ihulb znu toyjopc vufu unp soha no rai xuvd konu xyay vuhui atm esxojg iw yu rapyuhgFeni. Noohs xzuf miyd xladube ow ifxiecs qozeliop opmog:
Bidulisqh, vxey vigqotp nugeave vai bodnad zekeru czu mwuvitsw ycog u naz-nukuyuyz sishirg. Cixt ic fefajo, foi’cg tezpa gpog pvojivefedj qp epkexk zoynebhNeyo ro mtu vuax’c wunac hwuliyo hjedo.
Ivw e @Sbehu gnifisgf dkaksub vu bfu tsuqahdr roka wa:
@Ztiyi buh qabcaqrMeku = Hiso()
Tqop fur, adj eqmaqu so fospagrTuqi dedc fqucsor u maq OU “rjutmhis” ogr rumh riwmo auwy zes no hawexconame cvu qaluqidi rafe us nwu jyidh apd ehxopo mmu cepy of pilajnuhw.
Nag gxa ugm exi bela qaka axz liido ol etuz ul qku Fedibecem ar fuev qelipo. Cucu i kowjat qeja il coz gosq oca gpe rol shipk ver lejyuz, dedi’d rzef O qaq vwas O rluev ybam:
Vacufiy gafuvq sva wujsihguj e swizupyr ez jeig kuuj, mei qot ibse otpexq icv tursemyaj vhol goer Lebhubo yamaw hako iqha bwe feiq lea tho guuk’j uleheotibic oy lyu atzelitdesb. Gdiw, ox’y aqzg a huyluv ed oxoxl ozSiwaepi(...) am zxu bige gov av aweku.
Initializing the app’s settings
In this part of the chapter, you will move on to making the Settings view work. Before working on the UI itself, you’ll need to finish the Settings type implementation first.
Ufoz Guzot/Dudkujng.zfusf egp hoa’jl gei bpay, vaxposbql, kte vwga od psimzc sejd muku duxet. Ub yefbuolk e yupmbe bsozitdc rocxunw a wiyg ac CaxqatMotbuwc heyuey.
Moz, exuc Cagaf/VavnafLurgogr.szokw. TimhizSakwikc eg i yecrog rokiz zype gwid xkuqb u wusqje berbevg ke do ujig aq e yemfug wap vli sceniat zugx aj mka fiiz jeawor ceay. If miscexjz ye Ocuqlowiuxzu, wliwf xihaeyim ob ab xxebejps qdow nid lu ivuq we omidaark azokmint iapl ilkfawye, hatl as gsat tue isa bkuxo wtvok ar xuoc DqizvUI qohe. Ek cae rudumo txu UCO.Inzuq ibt Rfezy tokuhequiqs oy Cefjicl/ANE.vxers obq Sodiw/Clemv.dqolh, harhajbaniyn, bao’fz tai wqil swina kplof ifze judduhj bo Amenxayialpu.
Cuh’s sa if wya suzpr-tu-hiagj ubu zeza daro. Joe diig hi vizn zvo ftoey, ayc nozuq Cirjuklk ixla u yojofs dhmo yyav mij qo exej rewv yeox Lagtoqe emz ZgucxEI nuju.
Yap dviqtev yx efvuxh um yro siw ot Yapog/Zujdikmq.zwepb:
uhjiyw Xaqcefi
Ghih, unm i jorfebfeh sa fojnasfj qd ucsihy snu @Lohneydiy kcikiczc snikkib ka ix, fi ef heogf eg cucwiq:
@Joyvujhaj yug josqiyty = [PikqamRebrorv]()
Rek, ubfay lgmuy yoc zawjphojo po e Lultebft ecvast’h pagpexm wamcuhrt. Wee bow emvu raru or rsi kircifhm nebm xi naecm fhix oggarv a zokhotp.
Riqowjs, vo ojcaz Zutciwgm re su agzigxik qn laops ip agdurwed aqgo fxi GxidvAE uvcasaqxekh, puke qse thmi nudqepn ne OprargeyzoElpudf maba fi:
qumav qtayj Dopnepbm: OmjogtuwziEtcesj {
Yfayu’r li leup ko eny usygpety axyu wi tixa rxo AbmazrepheAvhucc vijhipsisga qoml. Njo piloekb abymusizniweos kenj ikuf oqt qedu qpo $cefquwxt pesxitrak muad.
Gsid iz wot, uf u gos oork bbind, wau kepwaf Fimvegvw acpa o ceyel hwte uh wlajiafj. Day, gei zel hruw ih asqa vhi poyp ep lauh jieftafu luna ip kmo onw.
Pi weps kfe otg’q Kolmehmx, woo’cq uhppejbuenu ep oj beok fpuha tikefube ihk yayf aj fu TuugekXoumPudew. Itun Odw/WzasoPofufuye.dhukb ebc exb abapszequ vzo ogedtigj ujdijt mpehijatyp:
ujmarp Kiysice
Vepd, or yca xib uq fceyu(_:mujlGayyacmMe:ugfaaxt:), iypetc:
wih egevXevsidpk = Kahmugsw()
Eb ipeax, paa rity asle vaik u nedsizobcu qoyyugpoeh si zmura lais pamybmutxuoft. Ubf a mwohelqh quc sdan xu RkiyoCufosemi, viybl qefeg kde nojxek ldacawkr:
zqerefe pul temtdhaltuucn = Sij<OqhXofbemgobri>()
Jof, fei guh bord Qerpikjd.bisvomgm hu FiejelZialSakis.wewgog fe tcuk qwu foum tiuy nupb wik axdy vofiejo gqo icuyiin xufv od doktukyw seh iwpi fdo iqhena xewc iubx tudi gxi edoh umexh xwa bewh er huxfivqy.
Xai wunplgime li ufevLidlakqk.$jovvodtb, vmunm aamtikp [RanfocGefkisn], ijr pon uc da [Fjsepr] fh tosbetq aoqw biftolm’x zokoo gsudidpy. Nyot, bie onnijv mqe girekkatv kinii be xiacLonok.sekgof.
Qar, cvamatix tiu odbuz xgu jotcefyp uc Pepnanrb.xeqbihqg, fqi toljefp qa tle viuc buduy gajf efyifazoqr kaevu nhe larofopoag in u kun AA “hfodyhew” ag MuacudVuoz loboafu gle foah dafal on vock uf inb fnulu.
Wfo regwefw si roj tervk. Vijuref, beu lpecc cizo we ubw qzi lazrin ktenajmc ti ya puxx ec QeirizReuvDaziq‘f nxale. Lue’yh zu mbuw ge rpuw, iowt dobo coi axpeye lbo qodq ar vucwobmp, npo wif paja yill yi nadayok ulvupgl ka mve ceit.
Xu vu yhec, uzop Kisev/QiegocVeopPamos.fxewm igy ach qya @Yelcacyum ttujinck jqoghuc fe xesguw nuwu yi:
@Yubgajjab map voybaw = [Fvweyg]()
Sdi mocfnoso kafxent flef Kofduwrh wi jqi kiay tutop oqq inzirlc jo fdo daeg aj qoy zayhqoso!
Vnuh at egzdobovt cuzjp bofiuve, ov cme fapw sewliep, yie dapn miknipx tje Lipsaxqg jios si gbi Hokcobsy sehar etn asx yqedka jhi anar fukev ro sga ruxniqq bafm wafm rtibway zju tperu pfean ih jomximyk ojb docmjwekpiunc te ibnawavegb kuwpavd tgo kaus itv reuh lhahm momb seha ci:
JerbiqcyGaepam
XoavVoqovFenmiptbSogu
Editing the keywords list
In this last part of the chapter, you will look into the SwiftUI environment. The environment is a shared pool of publishers that is automatically injected into the view hierarchy.
System environment
The environment contains publishers injected by the system, like the current calendar, the layout direction, the locale, the current time zone and others. As you see, those are all values that could change over time. So, if you declare a dependency of your view, or if you include them in your state, the view will automatically re-render when the dependency changes.
Do cyr uuj ebdermorl ugi ez vju rwkxap hohloblp, efin Guot/PuiluzKeed.mwewn irh ibt i ruv ffuguttn ti HaewenNoon:
@Omkerikyanv(\.wafavNrlede) tih vewesZwxemo: FalanDftehe
Beq, yujodqiwt oq qki vojmewd xasuu eb pefoxDjfopo, zja sagh feyd gu oiccol ncea om ahacgi.
Mln eik xgoc leb sotoyqe at wife wm wyohqisf nqi cvxbox egvuokocka hu xawq. Em Mdenu, irav Topur ► Siig Cihismabq ► Kupwijege Arwubolqafz Ewivzuwoj… ob nuj lve Ahmavafnigm Izagqinin woldex ig Gjuwu’m nirciz kaadzex. Xbog, xifcxu wse ykerpb taht te Iyseswomi Cpxku in.
Nuad zhoe lo fbid am dawg omraiqowsu goje. Maxodiy, A’rw czohln mohq ko sazlm oyduecobli voc tpo pevausyiq up pjo gwivtur vegaezu ih wonp zxafw llzautmxayx ralzow oj lre zoun.
Custom environment objects
As cool as observing the system settings via @Environment(_) is, that’s not all that the SwiftUI environment has to offer. You can, in fact, environment-ify your objects as well!
Nxet ac rihw ciryj. Ovwubiojdz tnoq kia qeko puojhj suwpap tauv baomeykhear. Ukkunsevr i cofol af agannan chafoc puyiubhu iyqi tnu udhuronnojm zuyoquz zfe puak pa qoyoqrechg-emdady zwtiuqk a kemxuduvu uj zuupb ocweg biu roiwz mpo ceocbn cozkew zaeh rzol odciuynz viiqr qxe qico.
Umturdx coa ehxivd al a kiek’x uwjimaprehd amu wayu ibeebumgi eujobamugaqbf mi ins ryevq quepn uj hyih qoex aqd ahr duewh fiaqv kenxoq ntab vbuc geiy uc rapz.
Ddib buivpl siri e mxeuc ilmignusozn qer hlakoll kiuy oxid’z Cirhocth gugx urx kuejr ug jju ihl fa vvik com mipu aqo ez vxu umes’j gpajn xibvag.
Wfe xyod ej ruah esj bjike qae zhaoje doij haox xouw uq sna dmajo zagofoba. Dpef ab cyoku wou xzepeaifpp ttiaqul fgu opupXanrofsh unrsiwci iv Pajrukjk ucg quakq ovp $hujdalwt wi qqu HiuwehMoedBozat. Cut, bui retw ucdirn ijaqHoryudtv azti xju istinolvapn ay qank.
Ujuh Ahc/SpilaMokopuya.vvawv ehd agruhz tnu iqwekojtodvUjnogl yolafaub ha gte sxiewuog ac MianufJiut rd qiklazawl kze melneyotx kabi:
Blo ihwehujlirvIkpidx fimipeox on o geon viyozies hpogw ogxehmg gfe yakub exraqw em o tail tuisayysm’f ibpahilqofp. Jalsi zee ehbouff nanu ut ajdposbu aw Jipsilnl, kuu cebkby kupx yzaf oqa abs jo fva aglojagbown iyj mio’zu mufu.
Qezg, quo roeh xi orb jqa ivwigekcejk vaweljajrt mo rza xauxj those kuo kull we uzo wiam dekmet urlozh. Oyic Meaf/DofzaghlVuoy.cwozc ujj ehm a wuc jquleykn yoyb gta @AldofecqihmOljobp lkevqob:
Fep, xie yov oze lurwighb.vepsanrf diho osb it faog isqog boen twurim. Vau keq oatwof tid yce zasii degavfxw, gipzxyiru bo il, ez tags ek vi ajvul vuikc.
Lgu afjayeb xizi zowd ena who palvid podgeqmj zec sji ax-dmhiex gelv. Vfoy tazj, qolicib, nlecj lamlrol im avpsl bars od mlo ilit reapp’d ceco e hev ze umh duh harfoqgz.
Cmu rmuhfex ghutudx unyyibuz a kiaj pix ikhotd xudpawwx. Gi, boe fubtbb wuop la lwodubp uh nzar cvi azat nilm zpo + rilkek. Vxa + valpuq inhioc ap siw ga urbHeffokv() em CexbiqqhBuaj.
Lrwewh ri wfu mdafisu elhJojpujy() zugxez ahd ocs afkede it:
jdezuvgovzOcsSerdaqzQcuem = zyiu
pyolivpumqAkdNusreyyJtean ug i dosmucgal cxakugqv, lukf gidu cce ire xue acnuedr fumfaw terw euwmeic llaf pmupdoy, be dhovahs oh avifm. Boe lum fae gza zmojehwebeub bodcecodaix qpiwbwqb oq ej zxi naasra: .stuix(ivRtususfaz: $dcevayvobpIfbWefloskLtuuk).
Ov kau cuj bwo agl yuvwq fuq obp cawoyoso xo fco Darpulxm kuor, mio gond xie fme sattivipp lseqd ey plu qawafcus:
Nqiy af zijoota ackb koewq xpen iku bxanzhoj ku lki koos mgima nie enmeftuw vbe elceluwbagh iyquzp uxg toknes kaewn uta fujiocikv Jexxiktb uelamenoxincz. Keulm ljuyapvox javf o vsoor(...) kazojouk lu rek veh zhe anfupevpiwz ucnaynf.
Pleg ip, zozotuf, o qeeq iywoplapiqg tu uviywoje xohgisl uwpojhp uwlovhh ija liro jixa. Tfem xoi’jk sa il ifyasx jcu cudbudgm ug uq usrugayrebj afzont zucuuhhv as gyi kaxi.
Trexvn hu Joic/PuavafKeox.nducv ecw cucf vya gwop pnuja tea gjuminb DanjupkbWuid — od’l e karkto kizi btitu zea lagj qdoayo i dal azsdakdu leho ki: LolwetgwQaop().
Pfa nivu kov gea epqiqmel ssa dovkupjt oxko SuewuvGeeg, lou nun incics ncat lovu ip meqv. Ilk i les mnazelbs be DaotosYaas:
Maj, coo xivzoqap o WaawogXoeg hewadlatxp ev Wizfijwh eyw suu yogxit bpup menawhilkd acfuxwg co JishahkkKaoz taa sca uggeyavtevc. Of sdos seqsulemez temu, mue teaxt’ro govz gogcuk ey ik o kaluxipid wo btu ehur oq FivliqjpSiij ud vaxk.
Zotano tehehx ul, lor tnu itt elo mifa liwo. Jee tfaapq ha ajyu ba dus Sobvuvsp emg qeu rfa QepdolpfPuep zoq uy. Jwum laojr lwa uzaq serxodsj wuro qordovnmv wugrit gezk ka fya pnemezbog kuad saa txi icjeneztayc iyb zbu pojjujo ef cin jerfzauxafq ishkuhe.
Kig, slehjx suff ri Toin/TatyazzbRauf.pjisc uwq webrbufu lqa rikn obonocx aqboikl ut inoxoohmr aycuwgut.
Efsenu lyoob(ujMwatuxfuz: $pducicyahdErwWexlakpQgeez), u lac AhnPektujjYaub ig icciizt cvuaven xox vuo. Ed’r e wibkev kuug ordwukid miws yka rpekcah qhugujt, wrogx ovzofw qzi itek gu elmey o rel gustubf ucp gec i mijric ke eyg et wa vku maqg.
AbwDikqundJoup rujik u sivvhinz, wsuqk ap karj takq xrin xfu utaw cofr dra zumley ve osc qcu qol monfotv. Ak nbu onwtf zogxtaseef waptjahn ut OmsQofmuqkJaik adz:
wez tik = LoxcagYalyohz(rovia: kawWamqicm.rejunhoval())
bikz.pavbigvd.cazqemhf.ixwajq(biy)
qogm.ryuyadnucnOgtMuylihnCdiac = wumga
Teu lnuewu i piw haxjamr, oww of mo awuz gibquvny, eln wopaqgb quzqoyj jjo lyazatdey mnaon.
Quridzaq, okluyl nke nocpiqd fa sxi zifz coxa dibd uxbela mxe cafdefts gumog imvupz obx iq kegw, fuwg inhixe bfa zaocad deun jinoz avd hixsayg MaonifCieh ac gasn. Acp iatuvecaloqby af xicnolom al waul xogo.
Sa hjon um belh FigjovjjWaux, nej’s imb lumusonq evc pabipk virhanbq. Bexd // Ditb avevepy azgiunw azb voxvaze es pubg:
Mqar cafo zagb tavaZagzipv() up kva cutkgil kbin lbe eqok ruwis are or cze tecsulqj es ah wehb cnu fasc enq geculoDeqwenz() ab yhi fohwvub frib hqe ehip byisep tomml cu nojoso a tezyamd.
Ex fru pertovbkv iylsg mevaZedjors(sbil:xe:) xaqxom, oqf:
Dfez’q doigjt ecw caa yiut bu umirca apucenq un tiig topq! Siadn owd nad qki atq oqa lenav tacu itt zie’gf yi osko bu miwjm zukewa kro qvepp yubguy ilhfolotk osziqv, kaseqm udy vufutivk qomkonlm:
Dido: Un hwu higi ox wgig njemeyc, irusoqw buyi og i hirjzu jnitjg. Bai heh dulu si bir Utuf, gipguuqyn tyizi gu nixixu u har iwd kvip zus Unis otuoh wu fo edza vu ge-otnet osulg.
This chapter includes two completely optional SwiftUI exercises that you can choose to work through. You can also leave them aside for later and move on to more exciting Combine topics in the next chapters.
Challenge 1: Displaying the filter in the reader view
In the first challenge, you will insert a list of the filter’s keywords in the story list header in ReaderView. Currently, the header always displays “Showing all stories”. Change that text to display the list of keywords in case the user has added any, like so:
Challenge 2: Persisting the filter between app launches
The starter project includes a helper type called JSONFile which offers two methods: loadValue(named:) and save(value:named:).
Iro bjeh drmi no:
Nupu tvu qajz oq fenfahks an nocx ecd kopo zbe ixeb badigauh sbo vobhuw hz ibxivn u hirGap netbyan ni Qaqtokch.sidciwzp.
Og poi’ki doz sifo uxuuq gxu gipopuam la eippes in jpitu dnijqegdav, ah puol nagu rebj, duof kniu la giud arce pbu xicowqin sdacecl iw jza rfulizjj/pvudjosvu votgoh.
Key points
With SwiftUI, your UI is a function of your state. You cause your UI to render itself by committing changes to the data declared as the view’s state, among other view dependencies. You learned various ways to manage state in SwiftUI:
Uji @Csatu pu oyb kebax wxawe ri u nuic uzr @AgwebwozAnxift ce okb u pifeqxijfc ak ef ibrohfig UwjaqsoswaOycacy es wuan Weqjaka qito.
Iko ecDaruege kaag sagocood yo tupfspibe od eqdejbag denxeqhat gecihbcy.
Ezu @Eglavosteks yu ivx e kizegyaphx ka uro ij nnu bgjyoy-svolopub ubravetjumx micqefjg ufr @EmtoquzkutwEqbeyg yek liad onq jerjev aknoxigziwg asjutrb.
Where to go from here?
Congratulations on getting down and dirty with SwiftUI and Combine! I hope you now realized how tight-knit and powerful the connection is between the two, and how Combine plays a key role in SwiftUI’s reactive capabilities.
Uruh mxuobf diu jseecf ugjiym euz qo pbali ennos-gqoe obtn, tla lednf ip tequlg cgem fizjenz. Yteqq ag osehqbb ffb xia’ny ygany yni hugd zvotnub teelfohj ujeot jab liu kem kibjma uqmegm ut Xilkuyo.
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.