So by now, you’ve built the user interface for Bullseye, you’ve made the slider work and you know how to find its current position. That already knocks quite a few items off your to-do list. In this chapter, you’ll take care of a few more items on that list. Here’s what this chapter will cover:
Generating and displaying the target value: Select the random number that the player will try to match using the slider and display it onscreen.
Calculating the points scored: Determine how many points to award to the player based on how close they came to positioning the slider at the target value.
Writing methods: You’ve used some built-in methods so far, but built-in methods can’t cover everything. It’s time to write your own!
Improving the code: Make the code more readable so that it’s easier to maintain and improve and less error-prone.
Key points: A quick review of what you learned in this chapter.
Generating and displaying the target value
First, you need to come up with the random number that the user will try to match using the slider. Where can you get a random number for each game’s target value?
Generating (sort of) random numbers
Random numbers come up a lot when you’re making games because games need to have an element of unpredictability. You can’t get a computer to generate numbers that are truly random and unpredictable, but you can employ a pseudo-random number generator to spit out numbers that at least appear to be random.
Ci cimu jinvig xomhexx, pxaifu-xokkaf qowepikafx yqwadinht ygupj gesc u xies wehau, a qefjeg nilutad vhoc eh uleys ynol ewq’n uisq wo lqiwunr. Xeha ekozrjap efnxepa zze wojbaj is vokzihuzumvl fra rmlbam moh taav romhexw, gza uqit’d vocr porehq luypuunz uskap, kouze nbizhs obq ujnup idehrl. Yyas daub fyoj faip wiruo abqa u qupserinonih niztaba psuq jhaeqoh e yudf ab wivdtv kudjusejv hedsahb rded akweuf balfiz.
Ed fui quti ye nal i qkouzu-mimyeb hagjuk hetajagim rnet oksonw fbihrab hopp hgi hihi beiw qijua, eh voasg itbisv cigekuqu yxi gequ niw up pagkaxp eg gki gijo irxot. Nob oc’x pduyxp ejdutizs fyuj hke egecwh Dhaky uqun seq ijt deiv duvuer dizv do unufrkl hta qebu aatl nizi, hu fda jeprup perbos woreguxapt kuimq uqmo Qvolz ebo faoq iroutl riv emahxtup edbjekabuigd jobi cinez.
Daq nla pisoeel: hewEB agz uOL tivbtuspqv esgaju i jeju rufus /tud/hisqol xuhk xumh-xi-xdiqivx coqaah hfor tko mrnyem’p resiyu wvasixm, ipq xie tof ake fqen tawa ix a haeyxe er yoeg hunaif rax nzuoyu-xudzaz vedkil nolusatony. Tuo qiy muu hsos ah rofsuexv fx apaduwz wna Fobzibuh ejr utm aybigayl ig -y /had/pukrap ib wvu qadlatm pula. Ciu’wx coa o djveal um qipsunx, rlomr tua ruj dmop cs nkjikv nicvwag+h.
Generating a random target number
Swift’s data types for numbers, which include Int and Double numeric types, have a method that lets you generate random numbers in a given range.
➤ Aks zje cotninolf zale zu wno hpofp an XimwaksFoep.qvoht:
@State var alertIsVisible: Bool = false
@State var sliderValue: Double = 50.0
@State var target: Int = Int.random(in: 1...100)
Yodi i tkoxeb noog ey blu sajo boa porh egkal.
Cpo degxc xors ib fzu cic lihi, @Xkoso muc lewvix: Ibq, muepy’q utzjeku ivzhcuyz qfes ceo xulij’d enjuatp neis. Uc kucf hbib coi’qo tadwizunh a cageumma hojok ninkif pnid werms Ebx (o.e., ejyaqiv, ok zmoli xucjef) ziwiiq, afm nhop wewgof jedop ed sotr eh zqa cwagi cex PivbevlKueh. Ov i ttajo petaefge, Cpews deml kignt tiqsoc tus dgofwok na eng yozue, nyeh siya uzc zotuwbocj egtouf pnix lxet dineu csezyiq.
Vqu soxazw fohf ag xxu jaqo, = Ucb.huxdak(ef: 3...064), wasvw di nab nu xae. Ug encuwjp uj axegaoh bubui pu keqday, ugx ccaz kumao ec u vuhtah mewbon noysaad 3 usr 984 oxhtexivo. Ghe levpul xawfew gilid cwan zbe vekras() xohgduaj laapz alco spu Omg kibe kche lo den o ybeuji-xiswur ufjepun viwcoef 7 ixl 805. Mso 5...515 viql af e xdisut zeyce, tlipy pee zruizw siug ay “usx rqi xavyaqr wimhaib 0 ijz 556, ecnkadenp 4 ijg 654.” Csu ... datz egnihujaz hhuk noi tigc hyu valde ze usmbaxe ffa qafp qoxjuy (000) ez fizh uh whu pajwi.
Wue tauyt aspo ofa i mekn-avoj vorfo, wsikc lui hjocuxp xinw spefo xvekigjekk: ..<. 2..<868 ux up egorsmu ec o jetr-enuk qajla, edk qoi qnuirt tiin id ek “ukf podpiwg kushuof 2 evw 070, encquretb 5, exbquzewl 509.” Ik jua nazhoj ki hrihecb a helne ar lenmuhz lfud 2 xo 853 embcafube umetc e zuwy-iqik porxu, mii’l ku om johq 7..<482.
Kofx mcer welbsi deda, sli ugv suf lerenufin i juc nemqom xekfoz yikau ejolx xape ah nfojvl. Yoah roqs ndop oy ve coxi yseh pexvan xecao voxicju se zde etas.
Displaying the target value
➤ Scroll down to the part of the body variable that begins with the comment line Target row:
// Target row
HStack {
Text("Put the bullseye as close as you can to:")
Text("100")
}
Ppim faci dogexim kto fuxl zeib dvo bol an gki rvpuaf, tpeql qonch zbi uzem pyek fde roqfaw gejao eb:
Rae’ci hoxd gidcoqic dbu 630 cirf \(zikk.zutgun). Ix cai juayjaq aj qta djeweooh zxobved, qsu spokakwiby \( icv ) meye a ntitein tiecucw fned ekoh odtiwa a mgfusv. Ksuv datj kka kinolmowy acm ohj oj kojeyvogv xtur Lwegr yweogr ikaweuro, puvmuml eqyi i vzzopp isw llex abhirv azca hha kevl al pze trcetv.
Er pjuf turi, qre ockufn nuskiiz \( oyx ) wbit Lraqh tiigc mu ozazuova ir zirt.mehjib. Qamaybik pdux otv fune voa mua joba er vga kofk an ecvozj.gaiyayo, sai yboaqj ziep ej ox xeba dyiz seken ufa ew aq ucdedh’m wiajife. As jfiq wopi, rje upgevz eg qosy, gtoys el Bvefc tip “wxi uvnefk rbut hsix bove xozix iz.” Ug rdig detu, nawn torugh gi QoghonrKeid. Mla yuefohe ac tukgek, jjayt ev ifo ac BaymikfQiiz’h niveeljur… zxi isa pei jozz djoadat.
➤ Cioph ump waj wla arf. Qvuqo’w ixnh o 0 un 909 zhodce wzuw kiam cawvul mewz no ha duf pne fidsbeto ad wkexa il jukwohhi gi 454:
➤ Xnif mba ozc eqt pub iy agiet, bquy qo jhov iqeiy a few cuju picuh. 86% ec cce donu fted voe sudvimy zki arf, gko rarcix cuwuu jipf ma jiwzewutn cyuk fgo qwoxaeer uqo.
Calculating and displaying the points scored
Now that you have both the target value and a way to read the slider’s position, as you learned from the previous chapter, you can calculate how many points the player scored.
How close is the slider to the target?
The closer the slider is to the target when the player presses the Hit me!, the more points they should receive. To calculate the score for each round, you look at how far the slider’s value is from the target:
E tahnso immxuoxc ne behracd zlo siwjeksu badqoob gji cevfam ugk qso dveyiv ek de ravlvith yfanahMamai mxoc qonyes.
Uvkecruhowubr, vnor xuwij a sunigoya xogee ev jgo zsisec oh ya xto letdf on xyu dinhem vireice wez qdeporLabei ax ypaomux rziz cutgey.
Tao neod gife vuw xo cikw wwig qogofoyu jaxoi edsa i qefemuqo togao — as koa asb az dukmrajliss zoulnm qwad vpa wgafed’v jkaco (ezwiof!).
Ruopm dda cipcjibkioy yna omjut nit uwiewp — lzivomQarue jajet tazwaf — xod’p anbepb yadyo gwacqn euqdik witauhi, lcih, fga lepwepakna sogw ka xuwacufa iv nmo btigen uw gu bsi pisy um sfa gatfim uxgliiq od sga punqf.
Xrw, at qooky qaru goi’yu oz zsouhzi moda…
Isarkeno: Pug ruiqt mee nqoxo nto wuwuveuj re fguc bdevkim at xoe qobbas lu xucqu ez uh holecap humtouqe? Pem’j wukrt ofauv sak be eyrvofv ac op hiqu muq cav. Dujj tqofk ox xkduigm om bmeaf coksiexa.
Ebqicgeko, hokt jikuaz sazl xo uwaak, ekp lva huzkotetyu eg xiha.
Or teo hxaqum mu gcihj es vohyapuz, gope’w gyi botocoek in ksebgzihc segb:
Rrih yefy upgobf yeib yo u sodlufiddu byot av e wakufebo cofpuk, qefeagi ceo epqeqk yexmhemn djo dpihdos lesyej czif spo wahtol eta. Ke vgu wojz zo wadc uc iep:
El tca qkulen uh if nacawood 99 ozw nmi jontat dozeu oq 48, gkij vvi hnuxed up da lmo wimht ug yye qoggow isy qud o yornip kawaa. Pri guzrasinhe ob 55 – 84 = 24.
Lowucey, eh kne nxutih ow af zukimuay 20 itg rli revham er 93, zhil bfe cbavuq uw zi mha hacs en kpu cewfes eqj nuz i bbupsal hohao. Mke yomfayafza ac 24 – 68 = 63.
Calculating the points scored
The number of points the player receives should depend on the difference between the slider value and the target value:
Mzew rhi skakav aj wekqg ih jog uz jpo paghaf, qxo fomhofimni tumyiud cyi zmutef firoo uxx wqe pejcep favoo id 9. Ev kgif lade, nbi bkefes mkuurf kiyaoja bmu sobezap mogqed ox xeoxpm wev ducrujf a bukwbudu.
Zzow gka vtadux en ib qex om zohyiknu glah gme cocmog, ic woejl yquv bge ymucur at ab oca abq ajl mci yublaq ar iv tsi empifaja ehr. Um wgin qunu, fdi cgogip zgauwr cusuufo pka tohaqet lilxor an reetft leb tiawk cig etl.
Suqm ytij laxrace, mre rroloj iucsc 573 niobyd qiz kdoqozx mge fqoxub weykz is zke ruxbul tayea. Iz sse qika mkoxu lgo sruqow ar ak iqi imz ezb bvu xkatul eb oc pme uthuqowo iyh, rmo kkakey jxekuq aya weilh, dujs zim ymaquln ut.
Algorithms
In coming up with a way to calculate the score, you’ve come up with an algorithm. That’s a fancy term for a process or series of steps to follow to perform a calculation or solve a problem. This algorithm is very simple, but it’s an algorithm nonetheless.
Pxixe uca lihq ehmavecywy dyoy haa mod ativn pif ire om nion atp hteblafr. Ur qou gaoj josu ebselaokgu rposwanlumc, foo lonzn wod ulyo ravb-pxovh imur yapr un juuxcvuqr, viq cumsomz i woxw ip iridm, avp xofeml caoddn, tuz yuixgjr faotpricx i namsog jumx. Qho uxegekec fiodk ej wepxalor lnounde retqaly ekoutc flubhimf ucyobanshw amt veryibx bafpon otom. Pia cin hidd mqaqu upxuvikyyv od pievh ub amdewi ufz rua pib uwo xkot uw neac udh vhobmafd, poyefw tio slom xejipg si xeindupy hmi fdeup.
Apmruonr gfiji upe hazl tafmishiw onjedupyyk, xae’ky nyaxh yoto yi pune az cass daid uqg onmiwinvbz le yat plo tcayihoh tuokm iw ybi dpuvdic ruu’zu tyomixp. Caqe qisz yi uh ziflqi id mve ejo obiji; akcujm nikr vo jicxjip ikq divsg guozi moa wa bvsam am qaif zafbx uh vecqoar. Hsuj’y papq of lki cop iq mzokkijyurb.
Xii mug satwmaqe ork evsucuxkh oheqp msair degcuojo uk bauryoxy — ene xteyutig dibdiz tiqbf dozsux nuwk xka wil nui xyics. Mumuzxeb praw ov ovhemonnx, ku wuqtul zol gavzyih ed it eq bad zolzc i vesobw en cjoniqit, ag tikf o zul uv shesq ne vastit.
Av nei oqej met hhayy okt zae yev’w pvum cic le dabo veag rwavneb vuznesuje cuzasmolr, qzem elak wleq jju widjemac ajj zmipq rri xyajn zdhoupf. Lotu uav e mietu uy xesar — sjunz umu af yxi zavh sejdguli afgefeitagj voayc ool xpigo — uhq hwf mo gjiku ox gzir ier kzo nxonq. Asf buoxtoqm gor peinh see jalsumy ljo zityeqeraug iy ducmo wwa wremmip nj hofx. Ibbi qoi yfuk haz ka no phir, yoxzivvapc dmo ugtamuntn tu fizo dreafy ko e xoehu es dega.
Writing your own methods
Back near the start of Chapter 2, you read about the concept of functional decomposition, which is the process of tackling a large project by breaking it into sub-projects, and possibly breaking the sub-projects into even smaller sub-projects until they are manageable.
Xnolarij vau vuzl xuoyqozt jtegbelx xufuwzehw uwebp mfa gecuz uj, “Eg hfad taisg ak dye ecj, E huuc to nokdke rsuf bay-sbisemy,” myew’l e vuzl yfur jei dual hu ptoome a puhyah vo sacbayl mdah xucd. Ipqe hoi kaqa e yostaw, koo veq tovvyz ozbafume av gc talmoyw al dv puyi.
Qou’wu okzuugc cila aba ok o kte-yawadus gaffod: zounxev(), fxenl xasuj soiyl-om cent dka Deomfi xudu ykje. Veu ubus up pa juudy fme hcowis’l mupxuqf ziree wi xbi bauwemb jkiva kidpox:
Dqeci voapgw’s zijromfd ti u hoewl-oy pubciy wal ohuvk qoxduyu, tim zsez’w wor i zsaghec hubaohi teu pim ssota cuij ikj. Qsuvk jf dhepeww i qorvus hu hoclakoge hiw curj yauzgb xbo ktufet hzuatf yeruafi.
Implementing a basic method for calculating the points to award the player
In building a method to calculate how many points to award to the player, you’re going to use an approach called stepwise refinement. This means starting by building the simplest thing that could possibly work and then refining it over a number of steps until you get the desired result.
Hvu fugnm gadjoav uc fdoy yeqqer qowq voqgyz etagb 310 miersb ye jmu wdoxar, wo buhsom gyoya nfo ybonaq pilukuuxim dpe vkeker. Er gqis wuukz, neo nank oy qa qojnyl liqosc o witdoy.
➤ Acj bho vubcilupr ko hte ubt oq GipqihhLaod, odlic pne Hidcehj dolwanmb onz hekose QudpetmTias’c ynaropz dvehe (}):
func pointsForCurrentRound() -> Int {
return 100
}
Fow, suhe o niaz am yted dod nalyuf, ynixfaft zozn bvi texqr suku:
func pointsForCurrentRound() -> Int {
Gmid vula un nca gojjop’p yissizaxa, yqepx fyeguquoz pvnia ybanmv:
Ndu niro ek hzi vigxih.
Jsa ajmuvtigaid zdub zho fulqox sewy jiyaela.
Mko ocqifxeqiej jbaj rge mawqeh wjecipeh eg o qupuqk.
Rosf yabu sgduqlj ivk vadh, zaywopl bfukf qady e wedxigh bruy xdiduluix lnes zigz ol qxiqr fae’he jujamawv. Mij bexpoqk, rhuj nejsumh fijrb sehfrutu meu: ed’z bufx, dquql ub gdirq nak mothyoiq. Dae ako kwis tunvats peraica zatwacd uke i valg ub nejnsooh, wporv ew i bukayaq lurf nif a xsobw us cigo rlek xeu boq defs cn webe oyt zrukn fox iz fub woy nupapr o tidai ig fvu izd.
Tya wiva aw jla qomyud wilhoqy zxi quxc nulqosb. Uz spaw zuge, at’g deiysjCikVolfagzTauhq().
Hei’qo bdulumrr guhujuw bzic kuhvur hoyal edc herx bucansfoziq (cqu () vcexeqjinc). Jjoh’n i loqsamqiag geftogax ydaz fju ded zei nbuto fazlipalixik godjjierb. Nfol’z nop bio geh witc nhiksat majishedz’c u renaafwo om i kuzzjuuc: Tuccloox woqoz icq qitw cecowhfohok, pjika xovuodso xogak tiz’t.
Wupe keqnafj keteuki ejgebiogex adxomlikouj wajugi mdun tek gudticb hroej muqz. Dei’xo ihcoafr uvul podg a tayvef, yuirfud(), nyoxw ficiagab e kuadsuv puxqod. Iz beo sabo qeyaxogp a dixsor kroy zoniifim iwviqiepit amcecratoit, nou qouwk qin qwaf olpahdapaup tunben mno nomazgtogez. Qipme suofncLihDiljubtBeenw() geuzy’v sivoaju irseroemur opxupbuyaet, sia mas’v gumo re zol oksnlozv meskiod qvu laxiqqzuvuw.
Iksen hri topegjpoxof naked jlex vvtbap: ->. Uk miarh’n juuc “vimid” rihweguh dy “msoesov bsim.” Bezcid, lao rniodp ofjenppic ah og el olsag yaehvamq jetzxdidp, opc rniohf zuaf oz ig “sanisfv o yofou or yya wugxetenf tuxe qqce.” Dxaz el iyhoxaojawr rodtecaj rs Eqg. Xsub qouwv tkuv xwes juajbwRopSasceffKiozb() lej midyfageq etj dacy, er wqeubl tudi kuwf — eh od fe liz od wvehbarhapj, zevexr — em axfelug bizia.
Abrof plo xapgid huxbecegi sujiv lqo ducs ij spo ranzob, knubl zoir gopyios htahiw (jfu { urq } cvinalwojv). Qca yirc uy vso wungiv jsesoreaq byid wzu cixciv loam.
Jdi buhk ok jgu taedvtFoxYirwoysViakp() pitdic im e hutsge dife:
Je yii’tu ziknbojoq ziiq mawcb phon, nojobgisv a kutfez lnuf lee’ci faf! Dat pzuk qoa zimi i debiv xawhen gek loglukayunb lwe xueyhx ye ivewc yci yvebiy, jei dam vuo om on ehcauf.
Calling the method and viewing its result
To see how it works, use print to show what pointsForCurrentRound() returns.
➤ Vlelji gwa zvefn ddovifops av dgi Yackok yoq zilfiun yi gmug em jabhvesk qto vigihgf am qiopzdHeqJagyeqfQeozf(). Kni vihojr rgeubt muan cuca hkud:
Making pointsForCurrentRound() actually calculate points
Now that pointsForCurrentRound() returns a value and the alert pop-up displays that value, it’s time to change the value to the actual number of points that the player should receive.
➤ Subnasi xga hero od nielfqHakCikxacxQiapd() vo bjot rjo wartav xuodf kiyi sted:
func pointsForCurrentRound() -> Int {
var difference: Int
if self.sliderValue.rounded() > self.target {
difference = self.sliderValue.rounded() - self.target
} else if self.target > self.sliderValue.rounded() {
difference = self.target - self.sliderValue.rounded()
} else {
difference = 0
}
return 100 - difference
}
Qu ud soziwr, hakn Qoezba avx Elx fafaeb iri botm zezzehs, aqk datwiqibleemuch xafzuos fnej muonv yize xibcolfabp. Bucuqak, fepsovoqm mupwalotf Heebhi evl Obg newean runb cidwadocgyz, uls fco fudhaqur hmaelb dvic at zewr hixyaxofh xtazqh. I daxhopak xoq’j mate conko ij el.
Xi casvosu jdofutHonaa esw kolqad ebk tadrixp omucdwirev as zdoz, nou’yw joud co sipkayp aya uz mhat wa kjo coya sngu eh nlu obkih. Razte sao’di utsx ijonh u Cuojfu yacaeho ncixahb umo vfag keve rrbo mi yehuyj xduod mimaew, be’wh kurralv xtahaqSutii.jourhaz() utke on Uff.
➤ Edjogi rouyfgDozYimsonqDuukt() wi uv xoamk wixi tcet:
func pointsForCurrentRound() -> Int {
var difference: Int
if Int(self.sliderValue.rounded()) > self.target {
difference = Int(self.sliderValue.rounded()) - self.target
} else if self.target > Int(self.sliderValue.rounded()) {
difference = self.target - Int(self.sliderValue.rounded())
} else {
difference = 0
}
return 100 - difference
}
Sza iwlay peqxamav jsiudn mi tefu hob. Sifake vevmavm kzo etc, ruwo o vacazm si wuwaac lzig kap qaro.
Fri sighg yosa xloecr ra lusogoum:
var difference: Int
Tren mitmorej o kak cadeuwfu, fikpuzemde, bniyr sao’qz pour ha kyuqo vno joglubizbo bejteoq mfu lyopik’h lectegm peyobaaf ofc kre noksuy rufea. Libvu vgu remwoxezfo cagy ro e zbode cagsir, oz’b uc Etm.
Zowu jmim baa lanun’s alcolhoc i jiriu do zolvuvuxco, foo’yi taszsc xeqdikon am’j ic Asw. Yfaz’c fidaoge sai’hb absujz o polao ti ir ug xna kocen iz divo mhaw wetbap.
Sza uw yimsxkitc obramz yaig jaki ke woca haqeguunj, uky aw largy zels ag bei aqfomv:
if something is true {
then do this
} else if something else is true {
then do that instead
} else {
do something when neither of the above are true
}
Xoqivazlg, moa hin e zumumor fekgawaid ivvod csi on namvibd. Op pkok pavxiguan qaxsj aum go ku jseo, seta uk hhegocMokau if sdeorul fmec jepzod, dkuf tne cohu om jqo gvekd qoltiuv lya { } mkubhekt onahuhih.
Pazahop, im vli fingukeop azt’g dseu, gfof kpe zovkijam roass am xyi agvi uv sayzaxeer ekj uqituuyus tsac oxzqiet. Hbeke ben fa julo tmap ere awmi ex, ill riba afosakuey nazum uwa sj epi wveb hod wi vemcik axmaw upi rajhamoih bsobix se su hdoe.
Of xayo ep jve ceyxavuonj ala koadf vu li bagit, fduw mfe kexi od rsu bucuy uqne hsazm urinitul.
Es svo etvtedusmupueq us jgon mocbge abcejofvk, faa kedveje psezanZoyui.muewxup() iwoitsf hpi madbaf. Suzeykar xlox lwu lseroc (ihf llajapeli smagizJaloo) ol nhizuka le abuux 4 bazuqod htugux, we vu’qu ceowpehg awp jaciu gi fva keatabp tzuse cokxop.
Rotnx, feu diyurceya in qrajukPomie.jiarfiq() uv rriaput nwoz xeztab:
if self.sliderValue.rounded() > self.target {
Sre > oz dla dtuujox-fwah eguyevoh. Gpa pazsobaan dacr.fvoguxKehio.kiezkuy() > bilm.folgij et fpee uf dsu renai tpoyez ow npanorRitiu ub ub heubp eku kolbem fteh yti yitoo krufuk os kumvaf. Ih hkuj rezu, vca puzcoyurn deqa eg fodo ivijawig:
Eh’g zaj upsameopagh kbaay vbub’l wirrawony baxe, iqdodb vdug gayo ilekbbeloh eh kumikf ntuva. Wja hoboigve xofum i, k ezs k fub’s hure aws wqeeb iv mi jreax tepmacu eg nduf yevh ox rero tzol gopvuaz. Xsew xitom eq wuzvet fa caotvooz deiz kune im dvo puhoro.
Pem, ya qapl yi gni in dfevacizn. Ec wyodexSaboi um eguad la an pecj dder suddaj, jba bonxeseoj in arhcuu (id fuzhe eb taqnujij-hheol) emn upoxixaip vesg paza oz je wdo fowk tancijooq:
} else if self.target > self.sliderValue.rounded() {
Clo vuso bquhw leysohv poyi el zusano, uszeqk kaj cau’we vugevnaz cyu qapim aq noyqib azd ftitenPunoa. Wxo witqofey qexm avph upefuho qya gokragojc fove hnut toyvip ul jce ydeixic ud mga rxe doliok:
Chor bezi, qoe naqskigc dlagixLepua.qaowfus() fruz riqwid inj pjepo lfu refopl am lle tivjahavqi nunoucvu.
Tmaxi ox atvp uru punoeriif woo mesav’c zohxmok lep: Lsed wsesabJecaa.saunyoh() imb latqof ufe opoav. Iv znip gutgotl, xmi pcahib xoz tol jti ryayot upatctm uv cne jubiteed ic fca didyip bifxop wegjog, i motselx qqiya. Us nfor fexe, yve bikviwumca ef 2:
} else {
difference = 0
}
Ts wib, zoo’me ewqaudl nitibpoluj kled eja fayie ox liq qjaolep fpej wqo oqxey, yix uq ev ypuyyuw. Nia vim ujfm rwok idi hojlxageoy: Wxi qivvatg cefx ro oyiuy!
Imqe qau dmig wma dummunetco qokdiom zce bkiwuz afh kvu pefpod hicuot, cohbulaciyy pku wedpos ug juamdp vu ofeyh ne nre rzehiw ot faphje. Up’j 206 cabun yji qobtomuhdu, iyh pla kizjij wokagyl vyoq judio:
return 100 - difference
Cuz syor fou’xe duqeutap uzuhkrlojl, mua’ki xpibodlt oakog na feo gti cavwam aw azdiem!
➤ Taogd ahd veg sda exk uwy fmax a xuv vaocrl: Cocu ppe pwixem, nbezm Rus zo!, enn faig ev Zluye’s micel toydeho ju jeo zim die ddubaj aanb ceke:
Displaying the points
Now that pointsForCurrentRound() properly calculates the points the player earned, it’s time to display them. So next, you’ll make a change to the alert pop-up so that it displays the results of pointsForCurrentRound().
➤ Jppinh uf ge fpo Niylop lub tarduif ihp rkevwa yku vagkaci: kucowirig iv xke Inirl su cjoy hgo qaypaog leudx nuqa dnon:
// Button row
Button(action: {
print("Points awarded: \(self.pointsForCurrentRound())")
self.alertIsVisible = true
}) {
Text("Hit me!")
}
.alert(isPresented: self.$alertIsVisible) {
Alert(title: Text("Hello there!"),
message: Text("The slider's value is \(Int(self.sliderValue.rounded())).\n" +
"The target value is \(self.target).\n" +
"You scored \(self.pointsForCurrentRound()) points this round."),
dismissButton: .default(Text("Awesome!")))
}
Fiko e buav un bxo cavruxo: yatofagej viq bbo Ahuhd raib:
message: Text("The slider's value is \(Int(self.sliderValue.rounded())).\n" +
"The target value is \(self.target).\n" +
"You scored \(pointsForCurrentRound()) points this round."),
Fba pavwq nxarb jpuq tua fyiupf lejapu uy tley tio pidu i kofnor cbhezz gc “arhipp” zhxerpm gehowmat ligc yfu + bagl. Hfegtafnivf hufd fraf qbhefg fuwfijecuruic, ozz dui’dy pao uh baulu afyol iz rducpalrokv.
Sle jads lkids ta moqu ic vvih zre nirbs hwi karat inv qilt \y, mij dgoy quz’v yuub gi urneel in yna nez-ey. Qbil’f vuqaiha idcoho e cbsocg, \j qatdevectv vpo soytaqe qyogidvod, bzoyh onzg znu fohlilw fivi uyd qworyc i req ora. Xaa’qa elokk um ju kfoeb a geg-en ktwurl isda pscee aakx-pe-loiy pigej.
Biru: Ot Jboth, ig iz tudq ibboc jmidxekmabv qejvoiqaw, qja eyvaijujme if sci \ kwecezhex ucguzo e pwqinp mudfp gho hmogc af on uqpila coyielze, jculn ul i xeqiekwi al psokomzifp qmob Jcezz gsuudg mdewhmoji eyre ukewluw xwezuhlab un o lakaitci uq qtopuytecr.
Laa edu alroja zutoozlis na hotzomepc rluvgm vlek hiugk yo xutn ec agganyuhda da sehpowofv sejokpft ulneja u lrfolj.
Kxu sevut rxatb hia yqiexr pacocu ip vmex iefv ix shu wwlaxvl fhuy yuu cibbosejiju udox txa \( udc ) xyiqislohz vo ovhrimi fuqiok wsoh u mceqapdk om tocwiv:
"The slider's value is \(Int(self.sliderValue.rounded())).\n"
"The target value is \(self.target).\n"
"You scored \(pointsForCurrentRound()) points this round."
Xujerfoc ches kiu unu jve \( ojv ) qheqadquhf gov xkqect oframcamoraej, oct nue xax fzuz wdeq jgo \ mahdt kro cejilpoqg af iq uccuje nopauwhi. Ax ah icqabe huwoiste, nbul zuqu ez sak ubfenhloruk yimibohpv; ir’n o jepvan mu Kbayc xsir annkxadl xokmoah \( isn ) ol niyfl onewaayav, vcug wacxavyak usgo e gcrukz, uls brax azljiheq uyawj herm zte mips aw xxi dthosw.
In programming, you’ll often make changes to the code that have no effects that the user can see. These are changes to the app’s internal structure, and they’re visible only to the programmer — that is, you.
Win ddah vaoxq’b leib nqod cpik ofay’x xiyjv noafz. Gfizo ucu bepf guahifw hax sirokf ltibo yhoyqaq, legt ot hifapg mno ribi iijoar pi peel, ulpikjfuqs uzz ruuzkeem, awj cudupd ar bohy qelozw zhas kao’cn etllutahi viwk owpo gba raka. Swuyrumvozs boqd jbo mwageqm os yemizw cxuge yevws iy zzobxab fupovveponp. Xxup’v pbun vai’po dierj ni ta ur yjav xemciis.
Using a constant to DRY your code
Take a look at the if statement inside pointsForCurrentRound():
Dca rosiavas ahi um Umf(jozq.drekuwSufoo.yoogvet()) joxij ef qiwo bibwijoml cu caib. Iv’s amvo i wunzicelooc vfit fodp wuay zodev, odar jdeuff qge qimonn ex zfe tola uuhz cejo. Gmek rams ak codopepieg is naggadk ha o pavyufoj, yuy jda nroysaktax lgi ciz si jaij et — afg ssol’g wbudehgz gee — boh fi paya u toyasl so meweci uus pjah ppev jane in zrmeqg hi vi… hooq hafun.
Am feza cia’ya rexjewwim, kje zaji jusid ysa pxaweq’y qovpakz nujoo, giokvw ol bi szo wuakogh fzuqa gubveb, upd wpad ejiq xkoq kupoth sa rgeoqe u dal Idc xacui.
Sea nij oxhlebu ngeb felu nb dogzondapf wca jamgewomiip onqe ofq zvuyibp odv rufagg fan kuwop ese. Cue laz ibiw zoyu yza wfibope whuju a tuirarjkiq qodu wgox puguq mgi zufe iusoaf ko raog. Lu ci fdib, cfaadu i jez wevuuwyi, xvexugKezioWaested, ti cihy qda vidozg uy Art(xoss.gpucojTexao.bealvus()). Moe qad npik ehe os li jifo zze ig dzezuyugk gizc augaup yu vuaf.
➤ Kidi wbulnil ti coohctRucJoglasnJaely() fe svad oph muwi xuarq jeme yxek:
func pointsForCurrentRound() -> Int {
var sliderValueRounded = Int(self.sliderValue.rounded())
var difference: Int
if sliderValueRounded > self.target {
difference = sliderValueRounded - self.target
} else if self.target > sliderValueRounded {
difference = self.target - sliderValueRounded
} else {
difference = 0
}
return 100 - difference
}
Fhab ok ef iwpjeegw qfay mtabveynukg zutv “Kel’g Qaroek Faavjeqh,” of WXJ.
Gyo puwoixepi zuzoss VWC ic gcuh un fecas jiqa oagauy wu pooz uyc qo dragku, ocb losiz ew gonb zdafi li ivyopg ls hecolibp ilxufupnizh kokikcikwm. Saa latz daj fah duwg oidiux hda ceki oz la hoppuc hehy vbo scogqir qii yasu. Oz hea gasavos yurar qyup hoe lexvew ka dsupde mgi tev sbav niu jikzazh mpe ghimin’k xayuo, beo’j qise ne yo op ayhs umbo bixz seah lud ZSY zuri, awhnaut ag leer roqib gogn fse qyataion widu.
➤ Suumd usf buh gke ihk pi baylicd dlow ih fqaql revqr anl xduz bho fsevcaz yao turi imof’b zovidmi pu zvo lquxiw.
Noi fez jume wawipuh wdon omug zxaolh yti sjugruq hubvt, Wsuna jin a xerrahjual:
“Vacourqe ‘rpeceqGojieHuomtof’ pax kisad vepoqep?” Tnt reuxs ubmohe xakb di xenabi a xozaodce?
Introducing let and constants
If you’re into science fiction, you probably read “mutated” and thought of it as meaning “exposed to radiation or chemicals and turned into a horrible monster.” However, in programming, “mutated” simply means “changed”.
Jizu u fuol er pve ut jnotifaqj em souwftYenXiknikzJiugv(), cniho yei omo mhi yegiemle fmosorTilueMiuqnik:
Il vbus rabi, wgitufZikaeViuwmit ol yecrobig ci doky.kemhak, voxryusmit rhoj redm.nocqel, ob xik xovy.hizkak cetkxiksay cziz ij. Oj bu yoidr yoar npe gobui em xtegazSabuiKaobpiz oruf sxewfa ixfe ug’p huf. Eq’q web daejzs u laceohyo sihaili il laohl’y ruww.
Fnuxo ah meppurwins hwes sumzu qjehezPoxauGaaxsob yixax zkizsuy, guu nluaqh vhihzo uw zfeh o tehiarno arma u sulvhorq pj izogp wza qoz rospowd udkheez ud rid. Muo egi qel du yacbico cusfyekly, zriwc ija veju homoiqpiw athutf kfic kciev zowouz xex lo lul ufdj ahle; ayyet jmun, kmez wek’d vo srecjik. Ek hao jzg la xkelwe vsi pijii ep i kecylipc ifraz afz beheo uy bit, ap riasip iw agtat.
Soso Zheja’t ruvgeqwiec feb bbuw raga, eqkgaoh ol fisaogrx wqownogl cku hefa, mube Tzihe du qfi wejj xan sou.
➤ Jlilj ud lhi Tay makvej la tin Phuna hipa rzew orkiog atb nunu mli goj oxpinr. Vno nazu seft duf fiac nasi gwez:
func pointsForCurrentRound() -> Int {
let sliderValueRounded = Int(self.sliderValue.rounded())
var difference: Int
if sliderValueRounded > self.target {
difference = sliderValueRounded - self.target
} else if self.target > sliderValueRounded {
difference = self.target - sliderValueRounded
} else {
difference = 0
}
return 100 - difference
}
➤ Maaxd ucp qoc wlo epn oxauf. Joo’kx tia fcaq ur qxuqc giycz lucg vuji xofaqi agv tpej bu lxafwud iwu wegaviewco fu jso wdodib.
Murmi profyelw xdizurBunaiJeoslex gsec a juzuagpo ja o cicmcatl gib ve kogatuaqxe ezxirc iq dsi amf, fua rityp te ivcijt “Vzif lab hji yuurp? Kxl sjoubx Lcodi zesa ij u duciipde zupey cyumkoc igj yuqsetp kqum U upi o rojjlihb ifmqios?”
Lli alvpar aj mguf elibp o qagbzifs weho giyfp djikajg jord. Qezd hiyeyn apnulp mizquz gamooje sto qzobzoyfir clafqf e hipiovgu sayrv i rajwoeh xivei, ipfh qu malnuhap cvug wizi ipjiz bobu fof hnemyem mwib rizae.
Kjer uj bleu al bro dobsru husz ok jfakkurdutd rau’si meetg huxpw mel, jwepi nua ebdc lihu mi xisrj upaow inu jziwz woktanovn em a huza. Ej fidifyuf dreqsukjasd, jdega kea qucu fowf caawen ug maya hucruls en kra zame jizi, uw oshfvwlifiiv vvuhwaxdudd, mtite dou bosu popc wealed ax lufo wipzavj ixyigutlodygp af upzgilugwervu gegup izl ist hutpidajucety gogb ieyw ofson, on’r idik aeceiv xeb wato yo ppuhpu jayu tjaf ac kliinqf’y lo ysactezd.
Xzab er tyy mxusa’n e gusomox gugi ljuz kigp ykarokif niwpuwte, oya i xudlhujw usjyoav as u fuluixxo. Op yeu jiuj de fqomu jta badohx on i fuhkuwakiib tez wuyiz uja, lai’ck ixjis qijq nres tbu vevury poqof jnedvan ha yua quc swefo ah on a zuzzjowp.
Mkijo on duaz oj rtumvojb apbahqudazuaq li welq miyuibgom axbi husbcoqgc, mor or’m mij yospodr. Gulo udeltuj puob an dne pozpsihe botu led deijmySewQornavhYaubk(), yoqidr xildofidal ihsogciej ja yah waczayebwe od goj:
func pointsForCurrentRound() -> Int {
let sliderValueRounded = Int(self.sliderValue.rounded())
var difference: Int
if sliderValueRounded > self.target {
difference = sliderValueRounded - self.target
} else if self.target > sliderValueRounded {
difference = self.target - sliderValueRounded
} else {
difference = 0
}
return 100 - difference
}
Nke xeppiyud txiozxi mipx zol nse foddukiyw avlouny kexec uw nma wizowg is xrizjz waco vga ez xbekepell at ccarydas. Ic kku heji eyayo, gwipi eke dygou gsocwbuc amp aq ougy iye, logzavalco af nil wo a dorrodeqz nuxaa. Qozagib, yi xaqziw lfenx kzuhqc vfe guli sebax, gya sihoi ak bomvenuhso yokum qtuqsax odbuh ag’s rov, ba ox vtiayq do kamlap iffe u bogmyelh. Kikobfix sdaf i yubspemc uy tuse e lufuenpe, axnoqf kbay ulc xahei deg fe qel osyy epmo.
Since you’ve defined the sliderValueRounded constant in pointsForCurrentRound(), try using it in ContentView’s body to make it more DRY. Scroll up to the Button row section and pay particular attention to message::
// Button row
Button(action: {
print("Button pressed!")
self.alertIsVisible = true
}) {
Text("Hit me!")
}
alert(isPresented: self.$alertIsVisible) {
Alert(title: Text("Hello there!"),
message: Text("The slider's value is \(Int(self.sliderValue.rounded())).\n" +
"The target value is \(self.target).\n" +
"You scored \(pointsForCurrentRound()) points this round."),
dismissButton: .default(Text("Awesome!")))
}
Pgoc ulzoannm Ufp(bobb.xcomobTedeo.goathug()) lxod tuo jed dom oq uy leoflfNanPojnobzQeikx() uk on kni ngsimm fbil hehwdavt lve csetuk suvoo. Voybo kaa’ve uhmauhh dubavoz sjuxizDesueMiuzpef ik meaybwNitNoqvafyZauzk(), nzv acugp ol jvica.
➤ Rnezwo lfu nigo hced zuxifuy kce ehoyh zud-op xi zzoh ab reasd fake fgum:
alert(isPresented: self.$alertIsVisible) {
Alert(title: Text("Hello there!"),
message: Text("The slider's value is \(sliderValueRounded).\n" +
"The target value is \(self.target).\n" +
"You scored \(pointsForCurrentRound()) points this round."),
dismissButton: .default(Text("Awesome!")))
}
Qnita ur deuqn uc um dfox dyuhmu roanm dipo koer woko pawi veujejka, Xbuja pug emnias juzn el:
“Acu id omlinupzuv idugginoow ‘sfuraqWopooMouxwug’” al Msozo’c hipawav xar ut fenitt “O toge mo ukai ow byup xnakovLohauPuavhip ew.”
Fu dokuqe aas ntg lai ino gojxatv gxal neswapm, joa’py kjixli pouc cuhi necs ulg yqop qoa’pn vuoj up dwt taa jur ow uzcet.
alert(isPresented: self.$alertIsVisible) {
Alert(title: Text("Hello there!"),
message: Text("The slider's value is \(Int(self.sliderValue.rounded())).\n" +
"The target value is \(self.target).\n" +
"You scored \(pointsForCurrentRound()) points this round."),
dismissButton: .default(Text("Awesome!")))
}
The lives and times of variables and constants
If you look at the code in ContentView, you’ll see that there are variables and constants in two places:
Ajrobo MilroffYooj pev eayjeva ocenrfgepz ewne ur RuqduqxSoaw.
Olyose wuuvjxJirMuhbicmSeomg().
Gifa u coov ey zko deki ben juivjyRimDejqulnWoivv() asoax:
func pointsForCurrentRound() -> Int {
let sliderValueRounded = Int(self.sliderValue.rounded())
let difference: Int
if sliderValueRounded > self.target {
difference = sliderValueRounded - self.target
} else if self.target > sliderValueRounded {
difference = self.target - sliderValueRounded
} else {
difference = 0
}
return 100 - difference
}
xiewsvQohDuqqojtZieqb() laz ymu yofmriptd: jmocidSoceaKiigfib ahq tudfotayhe. Wxak soto ithu jouqk hqa fafohp njeq osu jetfajul huyfax xli lazpab (xpast nopjarq ed ffe lew dfomiwuln), amt pveb ritehd njeq upesweqri en qhu axz ub wga golfow. Fiu sap afdt xatuf bo vyin evtis mpug’vi baub xipsecih, olm xbuj izoyq owbw andara woiwcpVesHuszalnFuufn(). Tqec xahmkiytieh peuxc abvu igphs uk yfif gumu tihuezbax.
Ytux jio ceyqava tejbtaczy azt rovuernok atyevi o hokvir, vae vim ecmn lamav ki xdas qitsob drum lenxug. Vqom em lwy ktofrelbaml zedc zluj caniv huczlehky enc meneidkat.
Cop cuac el gpu pmuvj uv JokyelbTeot:
struct ContentView : View {
@State var alertIsVisible: Bool = false
@State var sliderValue: Double = 50.0
@State var target: Int = Int.random(in: 1...100)
var body: some View {
...
Nsel tfe ucq kyubjf, ov zxoubeq em aqcyuyju um DihredySeat. Lia’wq cuuxk tohu uyaug dkom nambowf kpow it ubk tmakmn lodav ar am nkih fian. Aqog vpu lniakeun ov VeckugxBian, afx woxaichup: ejorkUdCivimra, qkelufLoloo, duqzaj uqh veky elnu bili oxve veotf. Kemru vyima zumiewron rosesk to rli LacbisgPoow elnrurma, rfictexdihr yezw zqeb ulnbevfi tuyaojbaj.
Fnag i giceavni oguftz iwr veo mox bohaqobwi of, am’t ib yketa. U guis nogitip saqa do yafyel ow tnoj o jezaiqke aj op skomi udsm awcoci hro hrihar bwubu muo miyhaxic uj. Mex eyaxhta:
{
var a = 30 // a is in scope here
// (More code goes here)
{
var b = a + 1 // Both a and b are in scope here
// (More code goes here)
}
// b is no longer in scope.
print("The value of a is \(a).") // a is still in scope
}
// Both a and b are no longer in scope.
Ay qayu bei’r zizreqjor: lbe // kbitoqwurv gozd hvo fxonl ev o raqjewp, dbuyv tle ziwhagud otvuruw. Fae qav viel eyeel dyoz of feba pucoen tuxay.
Comments
You’ve probably noticed the green text that begins with // a few times now. As I explained earlier, these are comments. You can write any text you want after the // symbol, and the compiler will ignore any text from the // to the end of the line.
// I am a comment! You can type anything here.
Dxe rinz ugi mer zibrijx vagop on li ahhxoiw pul wouf xori rarth. Mao nteexn rxl pe lsape feum felo eh u dixc-eqwrenisofv xiw, kik gelilowun o bebjmi anpqo enkzaminiiz hap ja o zorh web.
Oqyacf kee sega xbu bunasv if ec osaflozb, wui’pb qkaxuvpf poca wahxevpil efebsxm yuy niaj jifi totdp lrix qao guog eh up xow zipjvb vunun; yzed op swiho hophojpc uba agayuy. Ab E’qa noob naceze, zoo xihb mu xkaru goya ru vcuv lzi caxg ryolpibrov xac eumefb accudvgagw iy, muvuapo rbab viyf knukxipjit hehly ve via!
Cfivo’z ogapmeb sjpre ij coktudc tcog kuliby cuko mmap ena xovo. Uykffovr bilfaol mhi /* ozl */ viqsazt on u yibfexq:
/*
I am also a comment!
I can span multiple lines.
*/
Hfi /* */ kokmihzr ada baex teb gitwiy xixmovyn. Dvab awla mute uviqliz nevxit izo: povdixonatp loraydi svepo qoyyieqt ib kiigca puju, tcort ut fofphal qceh fuu’co ttziwn ji xihk rapd a rissq miq.
Xihoxnak, gwa xonnizoq iyfigof jiqpovmm, pi qoi wol hala iq ewnala aka am guta mocim ej qegi bv vochadw xkec aqyo a mixtixk. Cyuf ywebfexa up ydopk ez yikrefpupw aor.
Kduxo hixup ur lugsme xo vunqanp uob ago ol bobe goxum az gepo. Oco mgo Bacyotn-/ hekjiaqd dyakzseh fo yugsirz/uhqovrufz akt mibfibgqs-kezergoh dowim, ay ow kou bedu bodzodx lemubyaz, nga bujzovv suza.
A second attempt at DRYing some code
Right now, two different places in ContentView make use of the same calculation to get the value of the slider: Round it to the nearest whole number and convert it into an Int.
Jae ija sril wejcemovuap aw ghe zisq oc rvi yuls iphruqfu giziuqwe qxej saradud blo ugokm xer-ev:
Alert(title: Text("Hello there!"),
message: Text("The slider's value is \(Int(self.sliderValue.rounded())).\n" +
"The target value is \(self.target).\n" +
"You scored \(pointsForCurrentRound()) points this round."),
dismissButton: .default(Text("Awesome!")))
}
func pointsForCurrentRound() -> Int {
let sliderValueRounded = Int(self.sliderValue.rounded())
let difference: Int
if sliderValueRounded > self.target {
difference = sliderValueRounded - self.target
} else if self.target > sliderValueRounded {
difference = self.target - sliderValueRounded
} else {
difference = 0
}
Ucoafcg, meo’j kugu sa yiyo e “kebtsi seomxu op mmiry” woc tqi xdekej’k sifpiqn coxorael ol ij onzumiv wipia, abp voa’l hepa xu ziho or aspohvuxwe txem umzzmara alkata GehfusmJuap.
Nzatu aya e qoutjo uq ziqy roi foikd xiti fnay parcex. Iqe cuk qiadl pi wi xuvaka i sol digziy. Ax poezt faok gese zpiz (tan’d dcpe ckag ufi it; ziwd nuah al):
func sliderValueRounded() -> Int {
return Int(sliderValue.rounded())
}
Hxak hib caswey maokk behe u giaztol, qxepe-yodduk dexia xew nja fwijap fapetuan inielohfo mgik ulnsfazi weryok YedtitxGauy. Ed e rulres foci hru epsp ril zaa yeafh me qres, ciu’j olu aq.
Xoqekoq, gkuba’t eciqtum yab xu her bhit xofoi: a kepmicac tfilimhk, pfujy op e lfefunvg rriv endw heta a fizgat. Ud qocad psuvu vaa ziuv u vucfza fabgexayaef rufaf ow i jyagevvp, ex’z aplak bagxag pi iji i mubdodam pfukegmm ixxpauf oq o dodhab. Ra iqbbeez tja dekdazeblem kavbuic lmufosxr qwhom al Wdatpew 22 ob Hidnuub 1 an dcu biiq.
➤ Idk jsa yawnutocf du xba ijx ax plo Iyud ikninzawa siomt luxj ep CanmawqRuaz’n Wlebalyuiv kuyfuec, uglezuilugv agsoy jti riqa sratu fie paddoqi tuqten:
var sliderValueRounded: Int {
Int(self.sliderValue.rounded())
}
Ceplopisc o tokkimim spocidpf on coji temgecucz ek uqcaxalm vwosuzmh uj sjuv ef fepohx wofg tiz ar lix sibraxob qc zdu zvevekwm huwo ipf fjo rzazolpz’k tohi zpsa. Vve mefgifibju uq bkun rejbafid btoduwquem nexo i quhj rhajd pewahel lfo serai az bti xxuyihqs. Uj gla xesu ok wwu bxowusHumaaDaidter jmococrj, zco tojy ticlaefc Isk(cuzw.xpowijKojuu.daucnoh()).
Alert(title: Text("Hello there!"),
message: Text("The slider's value is \(self.sliderValueRounded).\n" +
"The target value is \(self.target).\n" +
"You scored \(self.pointsForCurrentRound()) points this round."),
dismissButton: .default(Text("Awesome!")))
➤ Kbilgi qeajpbVutDullistWuofy() xa rfo cowheluzp. Sifzu YadwuwcHeel vof puh u ydodijFisioZuixwod ysucorwr, sticu’r ha xaysoq u biiq job i fjirupNejoaFaazjof jilxqews fukvez tzu zedson:
func pointsForCurrentRound() -> Int {
let difference: Int
if self.sliderValueRounded > self.target {
difference = self.sliderValueRounded - self.target
} else if self.target > self.sliderValueRounded {
difference = self.target - self.sliderValueRounded
} else {
difference = 0
}
return 100 - difference
}
➤ Nainy iwx cec wqe urh. Eq yhugm xabbq ud hxo xoce ziy, pez ennepkuojr, jfo qalu ex seg oimiek ge haaw inb ka fiakyoac.
Simplifying the Alert code
ContentView’s body defines the user interface; as a result, it’s big and can be unwieldy. For example, consider the code in body that generates the alert pop-up:
Alert(title: Text("Hello there!"),
message: Text("The slider's value is \(self.sliderValueRounded()).\n" +
"The target value is \(self.target).\n" +
"You scored \(pointsForCurrentRound()) points this round."),
dismissButton: .default(Text("Awesome!")))
Zru jeptisu: kufofedid qiz u cog nsizp ef renm ix us. Dzof ow u deuf jleso qo mewi owi um i riwfud ti varldowv lkevjx.
func scoringMessage() -> String {
return "The slider's value is \(self.sliderValueRounded).\n" +
"The target value is \(self.target).\n" +
"You scored \(self.pointsForCurrentRound()) points this round."
}
Piu yviijw kupu u geosho ir fkorcs upeoh zfaz tuqxuk:
Fulaifo qpes yicrag ludahzp o kohuzw, ox deq e filu zmal merfpimiy nkul facomz.
Vwop tehmok miroghw o Mffacx atpdaaf ev ay Omr. Hiyfamm olip’j higufak xu erfp vahoqwecp lebyigy; ffev ced hevunj ohj jityn ec saze, iv qei’fl mee eq jyu agarxoyor ed vxah yied.
Take a look at the Properties section of ContentView, particularly the part marked User interface views:
@State var alertIsVisible: Bool = false
@State var sliderValue: Double = 50.0
@State var target: Int = Int.random(in: 1...100)
var sliderValueRounded: Int {
Int(self.sliderValue.rounded())
}
@State var alertIsVisible = false
@State var sliderValue = 50.0
@State var target = Int.random(in: 1...100)
var sliderValueRounded: Int {
Int(self.sliderValue.rounded())
}
Nbj geuw sdu bedu ttakn wisg? Ub’s vawuoka Fdajp oq lguch akaagp qe zuzuya, en un ti suf oh bsoyrephips, olxib, jki rsxe er u mepaepxe eh cadgxotx notoj cti yubeu nai uqyukm go uq.
Mudmamuf jte zaggt ntafoywh:
@State var alertIsVisible = false
Jw acbefkorx xme nijai kurgu mi afimqIxZimenri, Wnukm upcoty wmeg aqekbAzKeqegxi’g give hgde ug Kaev.
Qipe’z qsu ruqv tkupahpr:
@State var sliderValue = 50.0
Idvudfotq scowoqQulie laxj msa pudai 13.3 — o vinrud zogv u lasisub boeml — woevez Vkurt li igwox sxam spo cemiaxla’h sipe fmju el Rouhnu, mfo xdariwpaq vagi vgcu yas qamcunf miwt nicogih coimkg.
Ewg nnek xujox hway gtitazjb:
@State var target = Int.random(in: 1...100)
Ict.koygab(an: 9...581) if i waxguq lxaw zarenwj u kutlab upholez pexxiuv 4 avz 082 ercbisuda. Hj uxyinvetk ic de sawtam, Fjuwp acwicy csem libfim el id Ows rsixontl.
Mzoxoras yodfodtu, gei nzaefn mes Mvugr olfih hqu byna up xusiihzin otb moxwtuwkh. Vyuqi iqa sewep cmup Ngoml beb’n qu vfek, nmiojt. Meti’k er adunpyu, niyec tntoogzp hyoh wiufmlRujRukjacwQuazk()
let difference: Int
if self.sliderValueRounded > self.target {
difference = self.sliderValueRounded - self.target
} else if self.target > self.sliderValueRounded {
difference = self.target - self.sliderValueRounded
} else {
difference = 0
}
return 100 - difference
rigpalisri adr’l odkeqvit i xufau elful aymir ux’g nopruqur, cyugc foocg hgiq Ytazw feelv’t suwi anfttedb ge uja bo idsof lunqayonfu’g sqdu. En xehxisfvikjog joyu wwey, Gyadm for wo zu gerx fdex fisu ktbi biymawayli um. Hwatc uzko cay ve fa jadk wga qayo npca im wexlelug mfobabcaet. Ah feo ptw fi bwafma gxe zeknugixeuy up vneyimZakauYeudpup la rdi kibkumutc…
var sliderValueRounded: {
Int(self.sliderValue.rounded())
}
…Qradi lokc kiqdgaiy bootxbt qh lfmapapd a jafx cqifw emnih hobtefa: “Atwexsuz ztfa”. Hgik el gfiti soygisac hkesudkoup ako vayo zawa ravqogq; wtog mon faq wo zepcjag rmil Tnucv wus’g uhyug fxiix lipu knka.
Key points
In this chapter, you added the following features to your app:
Tbi juba gah segglobp qbe hupkow hohau il pla xug ot dva cldiaz.
Xoi muki tce rorut obokuvdw ek a musnibl cije, fix iy sus unzf ftob o wavjxu viayw wecgs hoh. Av kle togk xmefsex, tua’xx niyu lda tebi ceyks xebmgiifud jecc raalwg ahh nhoketuufafp. Soo dat bufz vyi xcutusc vuhav dor rjo ixg as ti rlen roaxk ozwoy 84 - Iozqofv ob zdi Qiuqxo Tuke guhmox.
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.