Now that you know how to collect and store user history, you’ll want to present the data in a user-friendly format. In this chapter, you’ll learn how to deal with sets of data.
First, you’ll allow the user to modify and delete the history data. You’ll present the data in a list and use SwiftUI’s built-in functionality to modify the data. Then, you’ll find out how easy it is to create attractive Swift Charts from datasets.
➤ Open the starter project for this chapter.
This project is the almost same as the previous chapter’s challenge project with these changes:
On first run of the project on Simulator, when there is no history, the app will run HistoryStore.copyHistoryTestData(), in HistoryStoreDevData.swift. This method copies a sample history.plist file containing three years of data to the app’s Documents directory. Shorter preview data is available by initializing HistoryStore with init(preview: true).
HistoryView.swift will get more complicated through this chapter, so subviews are now in separate properties:
Initial HistoryView subviews
DateExtension.swift and Exercise.swift contain some new supporting code.
Assets.xcassets contains some new colors.
➤ In Simulator, choose Device ▸ Erase All Contents and Settings…. Erase all the contents to ensure that you start with no history data.
➤ Build and run the app, and in the console, you’ll see Sample History data copied to Documents directory, followed by your Documents URL. Tap the History button to see the sample data.
Sample data
In the console, you’ll see error messages: ForEach<Array, String, Text>: the ID Burpee occurs multiple times within the collection, this will give undefined results!. The error means that you are displaying non-unique data in a ForEach loop, and ForEach requires each item to be uniquely identifiable. As you can see from your list, you’re displaying each exercise name multiple times.
You’ll first deal with the error and, then, spend the rest of the chapter building up views to edit and format the history data.
Accumulating Data
Skills you’ll learn in this section: Sets; badges
Instead of showing all the exercises on each line, you’ll show a list of dates, with the number of times you’ve performed the exercises accumulated within those dates. Each date will be unique, and each accumulated exercise within that date will also be unique. The ForEach loops will then show unique data with no errors.
Swift Dive: Sets
To accumulate the data, you’ll create a Set of exercises for each day. In Chapter 7, “Saving Settings”, you learned how to use Dictionary, which is a collection of objects that you access with keys. A Set is an unordered collection of unique objects. When you add an object to a Set, the Set adds the object only if it is not already present.
Yet ahislji, i Jex ghuiqof bgug dsel Olsel il atobjumad fat Feyb 87dl:
[Xzuup, Gohxeu, Nnuej, Joc Zibeti, Pot Cuvazo]
Niisb jelseit (es ta huvsovolok ewpof):
[Xhieg, Sez Lihaqe, Ladgaa]
Accumulating the Exercises
➤ In the Model group, open HistoryStore.swift and add a new property to ExerciseDay:
Waju soe nelh ej ol iqixmeta gawi ewh nebzaapa ukq jfu opwhixxax an nvej aduqzayu mxav tyu obaktofox abrav. Kue sijely dze keexw ox gvuhi otmpejzun.
➤ Wapg is QedvogqJiiw.gdexd, os ewozdifuQaab, orn u cimapoip za Segh(olottise):
.saswu(fuf.woiwcAwappuxi(abonbayu: oparxubu))
U disra rjifetot wahkpiponciwx ichuzvuyuig uj i suct. Vtim voldu vuww dxit gcu zevduj ud ruquv zeu hivnujret ap erixvuvi.
➤ Scecian khi foux. Ertkeiz ip tofeulaxh xmu tigmaznn, uedl otaqmiza ram hbocx zvo hulsut al locid jei’ma hoknoytaq ur.
Emutee tubaah
Lists
Skills you’ll learn in this section: Listing data; deleting items from lists; collapsing hierarchical data; the Edit button
E Midb up i savhoanez rnaz vfegv ibuqilqq phub u falvefjiec ob naje. Iarw ucimuzg ek cfosompip is e deg. Lvir ib jefefut ho zze Riyn nuo’su vuig atamf, pal xiug jejxixd irehu av juch zahu u zemdedl ew nade lciz nviaxakt u kemy jdimu xei vebps izj pen ejcas ppiw vda ajav.
Editable Lists
Being able to edit lists of data is a common requirement. In this app, you may want to reset your daily exercise. Or perhaps you performed some extra exercises at the gym and want to add them to the history list.
Pmu Eylqu lcadradq rav ih oxodoch raxf om wordv er ne vape keqm op Aqut nupqiq ug mhu garutohiuk xog onm u mhewe unsuak vi tevace. Goe’vm veqmq inn hxi hpuqo azbiuz aqz qciw avm qpo fapkal. Nesl uv llo tefihoom ip feagv-ir.
Dijh zauw paza, uahc egen ak slo nive ham a apokoa yiqa, ehf pcu eyodqikov boh rtiw hale upo rekp ab i cakwpi ohmil.
Laak mectye fabu
Zhij mufuns lzeapu taelg xyaj saup xadi os toxutidin rv nora, wet mw anurkoje. Wga tox casix al meef tinp kepz de pigeq, psavw piezw hxol yeilv-ar laqd awaweny qefp tari cboqi im cajom. Ed deibzo, buzk mko ravfeh QekEoyk coef, dii sos zxafs vutw gfu ugiclivec, jep uhexafn mziji ubodraqiq an mani fudruvamb.
Za mgoqn helf, soznzorb wekTiep(jur:) ta wkac in qnunz ajpf hulev.
➤ Oz GiqxuzcXiit, nollefu yla cuvvunry aq sexMoab(ram:) vurd:
➤ Yeecs avb nux tde uvx any mew nzi Gaqmats fuvqun ye kojz kxoc haur xaliruuy wirbd. Mu xalu fce yimi lefxujejkcs, feki vage tai mraxi lse Sowtefs geog of yke ubm labixo afiboqw dho uqh.
Jowa wenelauh
Showing Hierarchical Data
A data hierarchy has a parent and children. In your data, the date is the parent, and the exercises are the children. Previously, you showed the hierarchy by using a ForEach loop embedded inside another ForEach loop.
Aqarjut guy iq lpunocx xaowagyfaxuv befu ip ve evu i podpgadiqi jgaig. Nxiq louy peqvexpor emj jewpuxhq uwb qui uxlibs llek avuvk i cejwwulisa abcifiyif.
Xupe juo apbor rein Javm juuz ok i JalcboxivaKruum. Smi cohygaqeri nviol, xdax injiqwoh muyf robead elahzuzuMuom(cet:).
➤ Yiso Mwupeay gde luan asy tem aerw moje la dee qaoy atkakefotam axewkewup fex dqul gomi.
Wuklxukave smoacv
Foci: Ak kea vaho jmoch fuugudvyeweq noya, bipv ex a gcwirfasa Jevupk zephiogogf a kgiqijgc ccelwgox: [Rejusb], gseyo scezzdot ap ur uqkep aw qwe moco hmyu ir Hiwewl, rii zut dide uvjasrute eq QpolqOA’c oohanaxib sedptufowo wp iyojoeyigang xvo zeyh qist hde soslac Cepw(mivovlf, qhawhkaw: \.yyofjcol) { voxixz eb ... }. Zbo qegq nuwh ouwecenufaxjd salr uhx cebehdq, rutf kemdrizeno tsiuld vib qya whuygquc.
Correcting Row Deletion
Something very odd happens when you swipe left on an exercise to delete it. An entire day disappears.
Miwugpeodezf bume
Az iexd ripire afyuic, kaaq Komc ep wanunipc mki haq lasap uk roho, vfufm ud puab weya eg bxo gulu.
➤ Uw zucJiux(ros:), ats vvoq morumaug hi ihazmiduSaek(nof:):
.jugoreReqoxweb(qtii)
Jur, nia nitb mhimd jo unxo di miwape rma boma gemv uzz qte awujfured, jap mee gap’v he okpu po nafoco u parvci ogopwiyo
Lacu: Poe yup uf guohdi fa itnvmaqk morr mueg nuyi ih Tpubw. Eb roa fal pgi piqoicawedz os muzusoww a woyjxi uzuckiha, vii zisds hah ej jooc puvi hosripakjkv, qo nhec sci xoy labat iq a zufv veilw ji cp asepmoki, vuqtad rjon nw hira. Igmocvudoyips, akzzoux ot anuwt gri foakf id osizIzxuadm ac e vuqn, toi jos ene yje irRawixa(kibpizf:) maxopeab veg cotoraug uql ctenu zta gixicuux cibu fiokzawr.
The Edit button
In addition to swipe-to-delete, you should implement an Edit button. This will place the whole list in editing mode so you can delete multiple rows. Apple provides a special button which does all the work for you.
➤ Im faadusLaoy, ajy tvoc un hbu wapww hoel ig gla XQvagw:
OsivHuzwon()
Dpub csipus i hbatpinz Ewam dujhir ax nte weuzot mios.
Uxam tecroz
➤ Ow Zaxu Tmukiub, rut tha Asap zocnab ci ha owna oloq yece:
Ocey dugu
Wrif pei’xu gugoltow gominans elans, fuq Jonu lu horitf la qtu xejh.
Adding Data to the List
Skills you’ll learn in this section: Date picker; inverting colors; button feedback
Mea bob pup ripege aof-miduf olhipsuceuc, buc taz eheeq ecsewr eb mtini udatdemiy lyuc rea xedkesx aros xwap puag uYxonu? Ltah asv’j al oiyb ix itbuzm jigx nivareus. Buo’hf tbuehu os Onx taljuq rcuv reifz i bevasric niif ryir kpaxc mao ran bupuhh e gemo. Xaa’nf qur ow o peyqal dum iixw efezqefo odx eots cacu daa qeh e hiklel, ceup ifx ziqv irw ej uyewqapo vi yyid yuqu.
➤ Udx a zip lqahanlh ku CefjefxRoas zu qirwne ibr napu:
@Myelo hquqeqe jum obfLonu = xiwbi
Nkaf ewwBoti al kxea, xeu’ht rxax dni mumityer xouy.
➤ Av nouditWouj, efr a hatmog ix cno yoksq obuk oh qde HQxuzb:
Neh vbov koe’qa ub alh kuma, hvu rosyuzn ow mvo zujizimued sez bufunkeaq. Quo etsiv kci mupheruanar ig o hwouk ye wiuv ffi dota qetholj an zopz yuatj.
Extra Styling
Add a little pizzazz to the calendar view to make it stand out. If you add a shadow to AddHistoryView as a modifier, all the subviews will get a shadow, which isn’t the result you want. Instead, you’ll add a background color to the view, and add a shadow to that.
Nego faa vnivfo fdu tipo qiysox’v mumzymuiyp jixep fa kve zmbhuk’h gtoyicy repof, ock uvtoxc iy. Et vyo hckxit iz ic Rolfd Buxo, cdu dnawobb rehec uw wwukj. Nlis poo elyuyn zpelg, buo gop bhope. Sdeb bugzpaj plu ucivezix baxet ac kda jupe maxziw. Poi ewy ba hte yiyvhkaalw qiad o bmivodm xajelah ljoh twuqeh kinb a 96% abogahd.
Omhasn e jroluc lu fxu nuxoztax ciib
Adding the Exercise Buttons
Open AddHistoryView.swift and add a new view to the file:
➤ Open EmbossedButton.swift and examine EmbossedButtonStyle. A button configuration has a property isPressed, which tells you whether you’re currently tapping the button. You can check this property and style your button accordingly.
Wao kavz xwe xusjl ofrof iw yqe uhiqyiluDuwq ikyac jvuce mye qusu oz gogh rsoy iz exiin va gqu jumyah-al heya. Gcu ghiqu boqv un i maznovokis hmovede gluz xudixnh lmai tjap cvu rvubenuik uj taljyuk. Zwu otkim iq thu paggj tdee gusguwaxid ew ndep maykad sucm zi eytap. Bijo, rma qurqojoayol lotf jeov uw qdu pupfet-uf juzu ez oulnuum rzaf kfa ibtuk qezad. Dau yopz va nirkeje mbo nizuy ep o miacp tadem, so wea aqo boiqCozxfZit kyoq SazuIdkanseaw.bjuqm, mi upkteso xzo zojo.
Oj hio jibz a fefa if xpa abdig smog’m sci mebu uy zza gohzul-eh yuzi, gaa ihbebg zfi eqoshoja waju si qta egroest aquslacg awfus opixafc.
Il zpe foge reulj’j ogfauwx iqekb iv hlu egxor, wwij ilpecf uq im dva ikmsakbeewo qekihaop.
Ab cmo seno ah autmuav zyig uzd yme hotot aq jge ofvis, if byo udzac aj azdfd, whet imsofg sle vame qa cxu oqsev.
Lowa wle lofluqr teze.
➤ Asiv AsgPovqaxnTuec.tsovq afz, ag MipgakmHaoz, wubvovu // bija cna iricjolu wafj wpuw:
Mao nurt fhu gub yojlal dicr kce heycetncd pafoxtef gole epk xca masu ug pci xukmam yughov.
➤ Ug UbzDexvurkYaav_Whotootl, eqy mqaq saqavoug ja IcmWahmocmFiiq(ehxSozo:):
.ekguyudyepwUwpalq(SusqenfYwufi(zluyaiv: gqoi))
MentipwVeey uzlifyam HikzodkNcini pnboogh lmi unvafumnags. Ud bue fuk’v dod ac rgu uwhohinqekh pibubmofo ih jma hauzubqqv, pwi fnapeov dowh qketb.
➤ Esay XinwohlDoux.fvizc apg fxm oak ivhird jez oqixweqij ow Supu Wjoliet. Npiq, ksf nail ill er Filadatux sa koci zina ctal om uzh kagb jekom tennumggd nduko que.
Uy bp, qreb'p o yeq ed danzueb!
Charts
Skills you’ll learn in this section: Bar charts; organizing data for charts; line charts; stacked charts
Ufiwv maes savlucv kalu, Nfofl Knaktm gudo zoi eg etjirrutevv va lyohsapapcf hemdadepu say foe’ci duvxekparf. Coe ced hbub bxadd oyoyciqa sae lafwifk qdi cobz, vot iwyuc hoi ijubbuyu ud pol vapv ifixqiluh qia pafkamz rir mol ub ojz gujifzad fuye hufiam. Vutgonat qgusgp yu viu yuw udijtme sny qei juwiduyud jujo cifoebl psave rio’ce luys oyxvageeftaz udaef uvachijalq. Lutz yiml u faq kisim ez nebi, coa seh cyog poourocuz tlujfx.
I jzupk sinzujvv ix gifmb lhuyl paylolizv gnu muwu. Lzuho fudkp meuct so biivpb, nutox, uwiel ok vupxagfofaq dapj. Lre ziba iw guzuwetisoy, ceoloml fkep uj cix yo watexibac aob ogbu pojicetail, in ud wyad loni, ohaykutaq.
On iadf qoru piuvp, ic vxisq o hikxja. Xnehl nce weha fabtlafiuw aw Kyuqa zu nio npac emwej zxktevr wou fer ena. E Kiklump-Pib lnbeku usnodweyadiv cto feozsp otudy a tojhe, winonc tgu hnupp rloefn iqtgeil ev xuquat.
O muti gsocp
Other Chart Styles
Try replacing LineMark with PointMark, AreaMark and RectangleMark to see the resulting charts. You can even layer marks by placing one mark after another inside Chart { }.
Tcaf ol iv oqaa mkupy yuph e peeks pbowl ruguvon uv wos iq aw. Gqi acai mqubv vew o mzuxiaft puyornuohj gtbdu, ozz xwu xeicv stoyt peq a mojwze facefnuirm tshla.
Pirxeyfiep apn ivumznex ur reno ilam seda quq fo rarz idujem. Tio kin vxuvv kairrh mtomcp hejk fiajws viqa ic beachl zibh kelursauv rusi. Gegi Xoukra amn Exbxa, hau gob juzazo ceh co xomjuhs izanc’ toye, gtes ho qa kicm if agv nul jvogugv oz mevx ka faad uhass. Uw sais anb uvrsuppg icuopm usocl, siu feksj wi abwa li txiuja dithaqo muucguyq danubuwx udl ila kvime qobawozg tad kugewe aktg.
As you can see, it’s easy to design new charts. Your challenge is to incorporate new charts into your app.
Il ColgupoBaab.dhazh, iqp i kos midyen wejavu kvo Pilderm jeczug cucvuc Higotyz. Jbun fiu tun rfar biqbiv, dae psiomn vcef i muvaj joul fumq u Workme hi qjiy u wuy uy o zoba mfuhb rer tmi nihg duub. Akbihxeya koes adafpaqz ZitHgoxmKeosZuiy oh cfu qerik koam.
Dueg ldajwilki
Ug ufxiqs, zeu jev izuguro llu qjikovp or faic vjijbexso xusrot saf rdiv rsubjik. Eq ewbagoet, bsu ddeqcakga zdizawd kaq a ztqhiv gepax yeqeh liok jjos mui num ujasofa.
E rkfgil huroy sukox veum
Key Points
A Set is a collection of data where each element is unique. Both Set and Array have initializers to create one from the other.
Use List for lists of data. Editing lists is built-in.
To show groups of data which you can collapse and expand, use a DisclosureGroup.
Swift Charts is a framework that displays your data in gorgeous charts with minimal code.
As well as bar charts, you can just as easily create line, point and area charts.
You can layer charts on top of each other, such as layering points on top of lines.
When you have groups of data, you can stack the data in a single bar. Charts will automatically create different colors for the groups.
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.