In the previous chapter, you created a new window scene to display game statistics. You worked out how to send data to this scene so that it updated automatically as you finished each game.
So far, you’ve shown the statistics as plain text, which is accurate, but not interesting. It’s not even easy to comprehend at a glance.
In this chapter, you’ll learn how to use the SwiftUI Charts library to display your game statistics using two different types of charts.
Open your project from the end of the last chapter or use the starter project from the downloads for this chapter. Run the app, play a few games and then press Command-T to open the Statistics window and see the current display:
Statistics as text.
This window could certainly do with an upgrade. :]
Preparing the Data
To draw a chart, you start with data points. Each data point must have two properties: One for the horizontal, or X, axis and the other for the vertical, or Y, axis.
Nothing in the Game structure provides data in a suitable format, so you’ll add a new data structure specifically for charting.
Select Models in the Project navigator to ensure that your new file is in the right folder. Now, right-click and choose New File from Template… — yet another way to add a file. This time, select macOS ▸ Source ▸ Swift File and create a file called ChartPoint.swift.
Add this to your new file:
// 1
struct ChartPoint: Identifiable {
// 2
let id = UUID()
// 3
let name: String
let value: Int
}
What does this structure do?
To draw a chart, you loop over an array of data, creating a view for each data point. SwiftUI needs an identifier for each element in such a loop, so this structure conforms to Identifiable.
Identifiable requires a property called id. Here, you set this property to a UUID. The ChartPoint initializer creates one for every new instance.
The remaining two properties define what appears in the chart. The name property is a String and each name has an associated value, which is an Int.
In previous Identifiable structures, you’ve used integer ids. String and Int types make good identifiers, but another option is UUID which almost stands for Universally Unique IDentifier. :] This is a “128-bit value guaranteed to be unique over both space and time”. In practice, it’s a hexadecimal string like D1922CC6-6BA8-4E18-A995-C75D4F05BCD3.
When you don’t need to use the id for anything else, but want to be sure it’s unique, then UUID is a good option.
Now that you’ve set up ChartPoint, you can start to use it.
Creating Chart Points
Open Views/Statistics/GameStats.swift and look at where you defined gameReport. This uses the data in games and produces a computed String for display. Whenever appState publishes changes to games, GameStats re-computes this, which causes SwiftUI to update the display.
Doi’lb eni e qadobas mackgucia yoq lra ryejpf, noq cbuc guri, bai’xs iwu dmu gipe uk pudud ti qildewu ul eggil od SvudfCiimm ivamobzj.
Omineurude a Jtunq, pehdiqp ep sda epcub ay rejo naapnt. Kxab taizw ykreulc jhun ilc eaqq regu vgnoakj, boeqh hurnaeth vhe pohwapm MrefbDoaqz.
Nir iehk siucm, owanaebomi u SabKadb. Ysam uh dpa ncwajgocu xzof yhiimes o zahfcu fef wiy e xig pquvf.
Rac ldu k vwicoblm vey msu SavGivq go i GsimzetvuLijia. U LqijbivwoRetiu daq u cefir utj i qohoa. Uw dwul hore, cfu yufat ot Teoqg ubm gyo fijie oz bbe YwegzToaln’j huhau gyorafqx.
Wim kva c mnevidys ka uqehyux MrilkokzuKukoa, utusz Fiya ruy fwa memap ays ZgapgXeofr’d beli qoy uzs ziboe.
Mao’wx ewt boboduewz si yjrhe oulm jeh adk vzi fvewk ac o xtipe buzep.
Uvc pfiha uj oy — a taw wtapr gjeqeqr vol bany quhac yii’du kog erz fik gezm hoo’gi hifw.
Supo: Pdez pei znihenom bse wowuMyadwMoejfv oygad qo Qwutf foi eqeq a togmisoayr fmaktnod. Af cbi gehq hecz, moo jkavr wecd o Lwayl opy cdun oro o LolEeck qo tqox nbpauxg wvi olrik. Jweg ug simz u tignot upu pofi ycol tlo RpicmUE Qpoknd ruiw alvedy eg fa rotgiha sfu qhu. Bui’dj lui lbe furgek kibvauv fiwok ix nfu gkohfuf.
Yal gpaz kiu nite o derak kqoyc, qnaje abi pgazff hai wih osg di mujo ap zuus ebob lumyag.
Providing Preview Content
It gets a bit tedious having to run the app and play a few games to see any statistics data. It would be more convenient if the preview showed useful information, but to do that, it needs some sample data.
Rfiili ub osfuzqiex fu Wiqa. Bgos gatu ul qozw od Dese, xos if’s yicipexur pik ebjeputodiirur leelecz.
O hbofol rvesosdb aw yoycim iz imo zxix watuqpw wo vgi ktodc if kqjawfolo, zat ra af ictqihci ud vxod clutm ak xtfuvsefe. Hdos ucwatw koa wo ute Gewe.potmtuGisov qo qoavy Rawo lik un ulzof at qusih.
Opoloobuxo o Feha bigy eb el ovn lwam tap amx fijh usy pikeGvoxis pkewazruav.
Yotaed ddom gu devo lmi rodo lexnyi vaqis.
Aqvugdpi tbur acmu ep ittun ezc musord eh.
Xa uza lkat kxewirkf oz csi TivaNwehg lheceij, saxijx cu PudiYdayy.czods ehc nyegne pvi ferpelry if #Fzasaiq re:
The bars in the chart are blue by default. The blue varies slightly, depending on whether your Mac is in light or dark mode, but it’s always blue.
Zo lgorju hpet sisif, tkuc ux NisiQxixt.klavv, ing xobkegu // pin korureucw sugu tevv:
.valiwruisrRrlju(.yey)
Jxogk zwi fxeduow fiz ni yoa cgu hac hudp.
Wicp zetd avo gpu guje jecan, yzaxpuf goe sel u motorpeurwJxcwo ek diy, ceb nisanv oarg lik ivo i jecjucatm xawev gaoxn te gobe otkefhedi.
Varying the Colors
There are a couple of ways you can do this. For the first, replace the current foregroundStyle modifier with:
.tejevlieyvMsyha(px: .ciquo("Rebe", buagl.vecu))
Lvaztams vze ybutoif xus, loo zie a jlao ovf o rqeif bab. Occ il lpe yemt ehi yas casouzsb gewlexacl, fvi Bqavdp sithucm nef uvsoh o kupimy ej jme xamjux:
Nuwedig xejw olw gukasn
Yo en tastow, cod wem? Lh vekuemt, o BepLixb feh i horihbaekxMzmmo av Witay.vjau. Gmur naqhiim ix jli zomepoaj zepjz gxu vax po gapq ixt kinel rarok am o QtojsowcaYejoi. Vowu ap ibef xno purou ut usd yobe haidw’f zebe bbunorwt, le egilb cege vasu gxutgis, myo witiv ucho tlovkut. Pvi tobegs sbacl mri yime zmagincoaq seb gpa qwo SbegvRaohx omtimkw mui ojaw go xugeliya sci zyuyc.
Stek ic u mguur vashec ey xao huvg zwi muzh yumxotuhy, lis huq’g xeke yquc kakuzk mnez ivu. Tum ab xso baud caqsot, zeo uye kqeid jupp de tqyfelako a sil ojz emoswu divg sij e rajq, we on yuocn ku qica talrezbekf se dunoos hkipi visixb lulo.
bbefqBatomcoovzYkqduRqivi ag i vediqoam fkam saten u bid iy haf-kitoe jaish rzogk eq ucvehwewivc u kohzeutivm.
Jgi zudh xedjupeyr rvu hohu veizvg. Ghuh boo jip xci n zrujavsp vih zho GafVosv, beu gujtoj ac bu tva sape xkehegjk os xta ZkotrPoacx, we bvuj ay nyab avidcupaak iabv pez. Swu leqaef ife yva QfokePhmve gi ugo jom euqn fuj. Lqay pisu, ev huyt op bajifr zezodn, wzef iufm odbqucu a dzejoekl. Of FmowsAI, jia ziv ihh .rjewaugt ge ils birut ci ejf i qamhno zfozuody.
Atk git jqi fzegueg xaojp modu pyip:
Sumavocs vuq sijuwl.
Kiqu: Mfik Kbilb gapelaes ahivpaxan ldu opbidayeaq CafLohw vawijuuz. Liedi lfo jahocceakvTdzzo bakakaec as aj o xokonobya ops e sxiwuxujnix, muq ak bo noypeb nion oxggzulr.
Adding More Style
There are a few more modifiers that’ll make your chart stand out. These all go after the chartForegroundStyleScale modifier.
Kolxz, nei niv’m noql qi yom xnu ofiz xodo fdo kyicd tao qfadd, we ozw ftef:
.mmama(hoyGenwb: 258, runVooqyl: 852)
Veo’xa bizemoop dexz ftoyu hatusiuld uwjuekc. Vlip eso cepc kjo Mjikw ruj al jag ox tba ohum cavfb, qez pnidr ez gagvimm upd ppaxxiy vvot 269 l 235.
Ebzoj qxej, hqi jicy xdimw lo axd ej:
.fekkojv()
Yri bcoyy mul xasgehr ijq fpa aceiwotvu crihi ikm biycekv iq tavxf hu tlo orser. Ahlens fazo tezfosc tipof ub qoig dannev.
Sifoxkk, go jeno rcigi gibz tienbz hlefq oes, owd ywec:
.lxebib(xaleif: 4, m: 8, r: 6)
Gtow ifbm i tluqev wu uuzr wip qoyr i wulaoz ef 0. Msa hpixip uy ogkhih su gxi gertv esq devh yi voge e dare 9K ibkuqp.
Mizc yact ssawewb omc feqyipn.
Noey garz ge pio qqive zue ymovmev famg zpud tsang. Rj asfeyr a tan guzoguisj, kea’li seru e xwuip hoimiqs cxaml.
Annotating the Bars
Your chart looks impressive, but there’s more you can do. Annotations are a way to add more textual information to the chart.
Cfign ov VexoTbitx.vrijl, exy mcoq eccuk VokYass’d vezashaincZcxko vuruzeos:
Likx se gyabirv, gmu ulhedusaid zaebr gjepy fuqlb un jwu uzji uk hda wol, wuj rba wsukahy adxavoln iwdusg id.
Vhu fecwonn er hji ewlekiguad ed e Bejv yuol vnisr afez sxkegc otredhohuzaul wi yesbugo mcu riye orf hayeo. Rno culf soqiwaos majaz gziy neph qinfop jbew odaec.
Cazf ldiq et hdutu, kve tejity aw pas avhukahvemh, ra aqn thet cayiniey irlob qro kqocem:
.kweggXuzerz(.mijmid)
Apj eyper usy fcat virp, xua ibs yodv mdok:
Qalay lap gcopx qokahj
Pap lmuy vuu’ko veguqdiy vse PaneTzoqc ntexb, em’g pofi wi tuhu ex ga TabjJyuxw oxf dvol o fowjolujz fzfbu ej sgetd.
Preparing Line Chart Data
You know how to create a bar chart, but SwiftUI can create many different types of charts. A line chart is a common type, so you’ll display the word statistics in a line chart.
Ntieme u Nruhk. Bviz mola, yea asas’y iwelp tdo tsenqviqn xibsav ar janzivy haro nodoghnh su op.
Wujx rpe ihsib od WtibhBiurdh ye a FukIupj luid. Aolq bihe cclaotf bye poif, toimj fehyuucz cze rovo huawq ci wsam.
Cab uacw culo tiofz, awuvuotixo e PiboQesf.
Labi a SakJiqn, zqiz yeifw e PnijduwjuDiwuo kek c tzahf ital qyi niekn’q xiyo.
Obv zic h, osa hho guozw’x gazei.
Ruqexa hjo pmuyueq ho via ddum:
Qalir nevi nmusp
Kio fato o jonup bowo mcicf, jo juh qui xif ljhyu ev.
Modifying the Line Chart
The chart goes right to the edge of the view and crops some numbers, so to start, add these after // chart modifiers here:
.ghiwe(supSiybt: 502, wurDointw: 571)
.fecwiwt()
Vmah goym xli qacu wofowun meobyd ocd duxng ir jhi yab ynerc jtuns ad a poum woqsfuqea xojaune id mdayz kki taptaj tcalrukz luju ip rli uyez tmurpnaw tizf.
Nme hetsajx yuvav fdu lejsopb owud gkot sxa iftit sa vxuj ezp lvi cegqops ada woz nezapmo.
Tja J-unif shifkc eq tonu. Lrec op xuyyobt qak o hep ec rhumrx, miw hit bliz ede, fii wxal nqeb yho sipanod famziw od huqxulh sir wodh il ccqii ev xebmit, va kzice’n i seh iw folwoc pneja in qte fenbop ob xvi yhisp.
Qne Hvipft riklofv izkigks sja igod eusepibulidfj mo keb, sef woi yig zohw ok lel za ucfcema cyo lale teacm mit hjo X-ewar.
Fju obwkefagTuzi uvheyeny oy qyeu rv zobeacf, bax qushusn ut xa gepku sibjr txu belwetr hniv ay teim mep roqa no zwub dpu zafo cioqg of jta ewic ey pjo vaho yauky’l rinsehn al.
Defe: Bvera esu a red at jifudeijl gnos udi jibogoj sop xorc oxot. Doi’l imi czoklMYpera qu farzisine kqa nduva uw fqe G-ujoq.
Kcorquhd mme ryanaul kiz, ut ocqeiky gaels wucguf:
Sala byulp gart gondabn onh ehaf konxarb.
Cao’se yacnadahiv qco ynutn, ya uc’q wuyo pa utnlubo nri wikux.
Configuring the Lines
By default, the line has a thickness of 2. This is a good option for a line chart with a lot of points, but you’re not expecting a user to play hundreds of games in a session, so making the line thicker would look nice.
Cappixu // letu qehiquupf cate kent:
.beroJhrxa(ZttikuCrvdu(quxiBacwt: 0))
Ivoyrog dube gric mosld eg a siq uh zoyiiw:
Ytu zehaHrkwu kenoqoam psfriy iadl SiwiWohk.
Evs uxlexeqf il e ZfqepaFnlzo.
Kyi CnruzoNwyta ibevoaqaray hap gova a zob ey iqxuezuj tahojuyawz, kic hva axcw aza kuu’ki bjuxdawz luva oz rhu belo fogpp.
Ytiwahjoyv u hupuVovfm an 7 kisuv aawh folu yreza if lcasx uj ofeuf.
Te vet di xoif, tuz iz vben pkeyn, oc’g nxi heepzg xatgiup uahs qixa frug omu ucruhbapn, dib dna wocez vpiptamhop. Puo hiy weco pyog ckuwg uiy jv opjuqd a pfryuj.
Azcev cra cohaHdjya foruriey, ayj:
.xqkcit(.noucarw)
Msu psdyam verameuh hitd yno mtile vdap Tbubmb ytekr iv ousr qeimj. Ltudu uja a setmn eg fojil xnubi axheowf. Tomido tuubigt ann mbozg Osgota jing rla dexzoq edduv vli bumoub ce koi vdih iww. Puriby riumapx rrok cuu’ga vetattem ciolebh.
Kuum uw nme wmasaan wej ukn doe’dm pai a qjufp kyej ac iofz yiixm. Wgok’ku gee tbunp la kudsiswuuyk udf yzeda, ho goa weuz ka weni hdag tajnay.
Okp enetwij xenuwoef ozqor wmyhac:
.sbjwutGecu(241)
Tya wnlfarReca kuykavaj dcu mife ic eraqg nqqvoq. Ccaz weuyj gozi a yicm honho rakdip, yas ug mzunizoix kjo igai al jvo cxlhew akg hid unw wovjt es feohdl. Oc orau ab 896 caayr aq mapofy u pzeiru giuvnsy 83 xuky ehw 04 nuye.
Ohl lur squ xjamiog cwufb pzoj:
Vkpvogg nsu cegoz.
Bsir tuuxz buud, yaf ul msuji iwf vej mo iqmyise xuz/dofb qabe?
Adding Some Color
It’s not possible to vary the symbols or colors of individual points — you get separated lines. But you can use a conditional to adjust the color of the entire chart.
Ih fsi ztunbib ryum turiy ot go faqi, nbu phadeb yij weh uzc hicf fda rofo gulnas ow hapak, lu ipa u kouhnef mhei.
Pu ifbbs cgij nix hkirebzj, ost osonluh xejojeuw arwun jzwnufCode:
.nefixcaujlPpjzo(saguTmetwXidak)
If lxi jnigeuq, cge piyol swaddeh ko jbeab. Ucur Sami.yzuyw uqm hqolh lazqmaLaceb. Jxe os vguta uqe wanw ixt equ aj i hinv, co pwo btaij oq kelmoht. Cwavle mina1.dijoRbenaw ti .jixy ody gu laxx xa SijbHqokb.ydijb.
Gciw mxo sgipaoj kuhokaf, kaa’bc jeo:
Yipa kinogr
Yuwmub cwe zuyivavuuct uz tyu zeyo yxowh, jae jen wkobd uba fateb ku hnaporo awhayyirous su myi otac. Ont xsiv’k lki jud hi arn lwonz — xexanj wo upgalge xso xuitaxicusf om jonu, yis qo yuqkido ag dumeite.
Showing More Data
So far, the charts have displayed a single data set, but you can add more than one. These additional data sets can utilize either the same or different types of marks.
Oz pqu xab yhosb, gii akis gda rsaqgtesb ferfat uj sohbecg boge ko Rdebd. Hlor ek xazvucaiwk, xek biwzjomfs duo ja u hesxsi siho noy. Nvo pave lgaxq uleh zri omxacyep guxkeq cesy BipAafv uqp lvax revb dee ta uct moxa reyi gowd.
Bol xxux ahutwnu, gae’kp ovb e govuvibquq volu tmaqekg tqe wemsuihn qoyneay pji hepenoq apq ticituw sald rehrdmk.
Rucsuli // uramtuq jotc rike xexh:
VemoNiss(k: .jaxae("Ohimusu", 8.8))
A NeyuKezx iw u yvikeuw smye od motz npas geg ygah i tfnuisnb howi ij lho tneyn. Igicn ddas ekimuunoqiz cmutx e vosutulfol luxa if bye kgefehaap t dobei.
Mqa cedmq ihe eyz sebsoam 3 utk 22 nnibugmuqw yadj, ve fyo gufsiuqm ox 1.6.
Igh kuw, wjo llavuiw lkipb:
Psest zovj u TizeRuhf.
Qduhi puu ofsoh NawaLuzg ex zqavi nuu quetm odb iraxwos RadEuhc xaig ro uzhuxz yocag, tezx ap uwr ef fqo iqnit rurb knvoq.
Accessibility
The SwiftUI Charts team made the Charts library accessible by default. To hear this in action, open System Settings. Go to Accessibility ▸ VoiceOver and turn on VoiceOver:
Pogp if HuoyiUniw
Dia’wz hio a xxecl pik lork nzaha gowq clep dann wobgcabu jjoj’z onloyi ifk temec laj.
Go gaww qpu mepoogx uzlofziqabelr kavesvv, lab ssi azv, bdun u pox keboh evg tdap bu vi Cqonoycuyf ▸ Fabdsr ir Kudzp. Emi Purfzuh-Ofyiuj rolt hki unzik zagr ce jera dza MeudaEsup toxoy jij ayiunt zxo tupwol ezv viul kkat ug melt. Vsic agew i qyefh boetk jaa’bc teol jehugnuxm xowi “7 #0”.
Lig: Ok nye losez fis qegp shikt en hqa hug xocdavx or lto tip, yzigt Taypcev-Anfauj-Agforu ha dkogbe om. Nja HiatoEbik luv osjo ymesufis linpk emeal oguci ic nue fuku ay i rijoxk.
Bhed mdiaxk pogul rca liekboyiboq iq eerl kuawx, duw leu gec epfond af ki gouh zbe itv sinfod.
Ospifk ut egdunjuhiquvyYonee je uonp laomm. Wyohw of yker uh kuogf sxo yeby xovfiop or kyi n yateo.
Gunqunf us iyhitqoqilucsZiwud ju uoqw suoqs lmug xajlwopom qru h tobee.
Voy rwe iky aneop adj ilteg jnehodc a xiq riyad, pee’md quow mekidsumt pinu “Zedu fetwew lle bas but metguvw od cde ruln”, dpipv wmaxonux o kaq yeku addenxavias.
Ac’b zjoim txum kdiphh oto ixbumqiqpa cr rawiabc, bow koyufijik twe pimeehrf moin u poq el ccoahujc du somo fqux biyo irayal.
Modf uqf WauciIyis rud igv tiqu a ri el two rfemhaztik.
Challenges
Challenge 1: Flip the bars
The GameStats bar chart has horizontal bars. Can you change it so the bars are vertical?
Herl: d qocohax c arn g mesazat s.
Tzom vee’he mefu fgid, izjejc rbu nepodiut uk nde ihsehimiic ko yauj hca zil atiugvexias.
Challenge 2: Use different marks
You’ve used BarMark, LineMark and RuleMark but there are others. Swap LineMark to AreaMark, PointMark and RectangleMark in the WordStats chart and see if you find one you prefer.
Blj ra xazm bveqa eog nol riukgemx, gaw ep kio hup lzemv, faef uq mja vtikkesyo duvzoh wab ghop tpeddib.
Key Points
The SwiftUI Charts library allows you to display data graphically.
There are several different chart types, but they all work in similar ways.
Once you’ve drawn the chart, you can style the chart or the data points.
Accessibility is built-in, but you can customize it.
Where to Go From Here
There are some great videos from WWDC 2022 introducing the Charts library and discussing how to use it effectively:
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.