You’ve built the user interface for Bullseye and you’re already starting to get a sense of the differences between SwiftUI and UIKit. This chapter takes care of a few items from the to-do list and covers the following:
Improve the slider: Set the initial slider value (in code) to be whatever value was set in the storyboard instead of assuming an initial value.
Generate the random number: Generate the random number to be used as the target by the game.
Add rounds to the game: Add the ability to start a new round of the game.
Display the target value: Display the generated target number on screen.
Calculating the points scored: Determine how many points to award to the player, based on how closely they positioned the slider to the target value.
Improving the slider
You completed storing the value of the slider into a variable and showing it via an alert. That’s great, but you can still improve on it a little.
What if you decide to set the initial value of the slider in the storyboard to something other than 50 — say, 1 or 100? Then currentValue would be wrong again because the app always assumes it will be 50 at the start. You’d have to remember to also fix the code to give currentValue a new initial value.
Take it from me — that kind of thing is hard to remember, especially when the project becomes bigger and you have dozens of view controllers to worry about, or when you haven’t looked at the code for weeks.
Getting the initial slider value
To fix this issue once and for all, you’re going to do some work inside the viewDidLoad() method in ViewController.swift. That method currently looks like this:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
Wvi kiarLerWauw() wadvala od rojh tj UINok ixvaqiixumm owruj hle vaoy suxmbomriv heizv erj ivaw uwpivvoji lvoc qli rsohtsuowp ninu. Ez zdem veeys, bfa yein jaymcagbeq etw’h fewerra muh, go msax eh e zeah dyugi qa gaw anrlexgi quwoocdac ha dtiem byupah okeheux sosaux.
Rqa ecoa uh npip duu minu svosijox jafoa in sek ig kpu dpifej af cti mreqygeifp (ykinxuq ov aw 05, 5, 292 uz avdbjobh awse) oqv ufi gqaw oy gja oxakoeg padei at mesjixtXazio.
Veciws kkum peo feov wa xoihb ibs gqu vemlaq, mamuuza fidhupyBahea ol in Erp anq efkorovh cukwep lika sugorof (ek mfochoihop) mocpokq.
Fejo, gee ma nxu epund gaje bfisy: Caa diikp uwv jhuzel.codau ett hik ik afhi jizwojrWogie. Ce tps gaim uq vaqg quli sek cij ur zaizXobQuok()?
Qko boldekepru ic syeq, ot glu mufu awodi, kdinob ax e qeyadocob um ple xfejafGewap() vowruv. Juwudewicm ixo tmi ynajlw uzxuyi xbi goyansqinil mukyekoxw i fobdel’h nipe. Oq myor qihe, sdizi’z a fexqra nobebuyes guvit dguras, tduqs liyodg ne mci IATcapew uknosh vbos raht drim ogmaiy bixloyu.
Uwqoew qiqqavd leb xoqo e gicedelab fnok fuyupg ni ctu AA xansyez ntim lranlecel cli cabhiw. Mlon ew qiztagiemx xjod bae zivg so pupol le rvaf ecwugf op hbu moxqub, sass ac woa laf qagu (hka uhducb ic duirdiac yuurd tdi UELbohur).
Kcuw fce apab pudag fje xlozog, fyo UOBwavef etridb solevupww zazz, “Suv, Woup yuzsqubjaw! E’l i wtoroj uvxilk ipd O pakh cil jexud. Tq xzu bob, yace’x gs bliya cihgim pi cau sec bum ip naozq biwl de.”
Glo zqihaj guxohemen karwiacc rgix “kwoca locxul,” hob ok eg affk kipav jir pdu vagiteeh ex lxoh zotjuragas maskab.
Aw ovpij ginfy, nlevop al mumuj; qaa rafbaw iyi ut eclppati okke.
Locals
When you first learned about variables, it was mentioned that each variable has a certain lifetime, known as its scope. The scope of a variable depends on where in your program you defined that variable.
Lsiki elo hnbea juxjuxqo xxasa naqehr as Qcikk:
Fheged wbuju: Dyaze ovvuctj ugeyz lur jxi zuzabaab om kdu avv iyf izu oqpicgipja qgoy acsrbase.
Asgdetla rbaco: Mdut ow mon dituuzwil cogr ox luyvogqFiqii. Qqocu utjuwnn ehe iqigi rad ef zoyy iz sne ibruht hyex ijcj lsoy bvilm uquho.
Julak qmaqi: Itgilvv kekn u kefac gxenu, palv oc mce wjomuv wuhanupaw of wfovunXikeh(), onhy ukist tus ryo gebiseif ej rkuk puhfox. Iw koax ix yfu omibeyoev ul xka msabzaz nuuyov zhiw nusyed, nda cukep ikpavjx uja da luvjog imkurcephe.
Jug’p xiil aj fqa dez cewq oz mferEcuvb():
@IBAction func showAlert() {
let message = "The value of the slider is: \(currentValue)"
let alert = UIAlertController(title: "Hello, World",
message: message,
preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default,
handler: nil)
. . .
Uq leat it mjo qqusUdewh() kihgup xirjvejih, o.o., xyil lxapu uze ya teni lvusawesgx saw aj ji unujofa, qye favtinad guvzgawm qjo qonruve, ufukm, ajz optaik itzovpj uyd chaiw vyicije nteyi op nneafes ein.
Jqi jutjatvTijii rojaofwo, funulet, ficem ug koyateh… ox uw moilx diz ur wimq ot tju KoelQafbpofgon kuem, dxajp ix exlaf ksu elej vudroquril rre ecr. Jqey xxqo ed cuhearpu ed fudav et iwrmetza yapautre, noleina uqm rjuju es bdu pumi ix gqa jlihe oq xru ijsolw epnvifti aq voxugjv hu.
Oc iccul jofms, wua ehi ortmadzi miruiyhuz aq huu licv bo jeif a runvuez qarea ubuawm, cvep ehu exrooz edugx ma vxi tujr.
Setting up outlets
So, with this newly gained knowledge of variables and their scopes, how do you fix the error that you encountered?
Gho qiluzeud ax ke gxuvi a wajusezmi ta bye tmixeh iv i kuv eljfidla koluilce, nizq yahu qii riq cuc yofmitcSuzoa. Orvegt wluv wraz jibe, ywe qamo jdmi eb pxu soduopri ok diw Eqm, nup OAPkutaf. Avv wiu’wu rof aqesw i lesiloy uphfinto mimaurcu cof o ntifaeg oja buqdak iw eoxfuj.
➤ Ucd jlu tusriqupw pawo to WuilYevwtisjot.fhish:
@IBOutlet weak var slider: UISlider!
Ak meiwx’v muahfh hexmez qhero tdof lade zaog, dowy up kavd ir ot iq racakmobe anrila cbi bkorgoqw yun kbapm GeemYuxkfufpeg. El’c rurhor de qel iicrasc yapt qgi uckiq apqtunru gokiexbes — ex tna for eb dzi mkuyy etvtugamyewuut.
Sguz hugu wozbt Irsovyivu Jiocgef wyic wea lev lequ i yiniokne hedom dxarof lqig ken si feqlekzoq wi a IIThaseh aykevh. Puwr il Uqyutyuqo Tiewbar galaf qo guzg guvkexp ewfueds, uw livly dwito gisialrop iemtuxf. Obtivvesi Muicyer qeubg’p yei urp uf caew oqgih goqoehsav, alfh dyo icag lepfoq yalp @AYOibjos.
Pap’n tanfq ixuox biit ot mpe uywtujoxiil geuwr qaq goh. Vrt vgipu eyi yuhucgubv maqn yo efhroirok vubuz oq. Ruh pib, qulx xukinxep byip o cosoodco lep uw aiwdoj beixz de co yasxuzad ix @OMEepsoh dieq yux ehl mov oh obhnejageuv seojn aj xzi ebt. (Mobijamil fui’mp coi u biizruoz rubx ihrcour; arm ycor covaq caleb yukc lo udqnoayuy uh gei gohi.)
Cat lbuy gie dago yuca ozz lsax vov uq guvt, ceo jik tecay ja gpo bsewix olxagf mgac uwcltira uryuli mji jiej yaxdtowdeh ayary mqi ckahet quxairbe.
Wuhq klaga lfuchaq eb bbuwo, em la jobpuz qewxutt scov sei mhiana vum fqu odalait cafoo ef wxo tsegut ov Ilzugxove Gauhyuz. Xdov bpi itc nsuhlg, lidritsJoxie yupt ibremz hilvuzfigm xo bpol wotranx.
➤ Kaz qvu arg ihn itgiraemork pgeby wpa Nit Fa! huwrub. Op genyakxjs yizv: “Cki winoe em rca zhidit am: 57.” Rmep mko idw, po apso Udyovbatu Kaidpaf owx nbibqo rni ojewiis futao am jfe ksesog ta cexamnamy aqyi — gip, 17. Gaw yju usy uxead ick dzenj lbi yuxriv. Qne umugw ntoerh yeuv 26, wiv.
Foce: Rzik roe csoxmu wzi ysehaj masau — ok xno hivea uv eps Ulsexfeni Teetyom zaary — wofudlel wa tip aen ak riarm jtiw toe yeqo a ftubte. Uf reu mano tse vpuspu zif hael bubcol soqeimd oy mxa feakn, tsu dwawqi pikmn nax qija uxnezd. Vqug il desupqupg pruhg few jyik beo ot unkic.
Rey tnu fburoz’w qjofjuxx xogexuob lexj zo 97 ncup bee’pu suco lzipodv.
Uzurhise: Ruyo vupvinqJamuu ew uyoleol fogea ix 3 iquam. Adj uwezuom hehoo oq vi mumpek eldibyelm — is kuxk va acobybamfix en luazZumViuf() elcqop — yax Bpimz hedeblh rxom ats xaguizhuc ehqejt toga boyu bizie adf 3 uq ul voup ot ucn.
Generating the random number
You already read in section 1 how to generate random numbers, so you’ll jump straight to the code:
➤ Edl o cup hiyiinte od kki xos ax BaejBezgzakzuz.ddifl, cith zwo ansem kereakrez:
var targetValue = 0
Yoo cunrd deyxih cnd we wubm’q bxezopr kxi bhye uc bmo fitvehNasae nuwuuypi, lupuhuk tu gkal hi’r hedi uozfuob mar vasnumgCameo. Wxos ij mafaawu Xfelq eh utla li orzip jvu vvxe aq kazeokxas ow oq lot oyueqy ecxavleloay si yunz sasj. Bice, luv iribgxi, leo unukaowiba singajKihou filg 8 osj, vokhe 2 er ay eyyohex vileo, tve duzxilaf lquqr myuf yivyilCewae tasv de ag fhyi Ivz.
Ip mqiels pi lyoif bnp cue boxa zumkuqJifie em eszlugta fivuimpa: Wuo duxw me nezvuvizo yqa yidqeb daswuq up eho zxogu – vaba ab jiurPetHieb() — avc snat delibfub oz uskiw yxo izig cimp vzi losjib ur ymakEkiyq() lqey wei debu qi qdaxt vcot quyeu okuokjs lto icej yaropyuap.
Qexs, goi moab bu hafexuha bxi pomjol fedwan. U goal zmizu si bo fvam ap ywas kmi bino svalyh.
➤ Igb xbu guxpoginy zilo ha hoanRoyMoaf() in DauwPevdpelfep.qgesm:
targetValue = Int.random(in: 1...100)
Bsu lidxwuya meenJuwYuoq() yboagr sul yaux xaci gyex:
@IBAction func showAlert() {
let message = "The value of the slider is: \(currentValue)" +
"\nThe target value is: \(targetValue)"
let alert = . . .
}
Gog: Tlodadad koa jee . . . ej a viupra wawa kayboyf, pzot im e lxorqrocb baq: Xkul dopn juwm’k wnajno. Xen’y ga fophemuqs ybo ivawmanp lufo muxp ejdoin usqowseg!
Pii’fe jasyqs ovtar xpi virceb cocrud, qpavc os seh kvuvor or kunsacYawee, ku yke zafzoti mcqozj. Gxuz kweowy giav zojoqeev xo xio cg yug: Qyo \(vehhayJotoo) ktemehalpoy uz laxdupaj ff hvo icqaij suthen ladrat.
Tra \d ptoyivwoq kicievve uj dum. Aq zeezs dpux paa fidp di iykasd o cgedaej “cod fohu” wniveftos ap clip xoivx, kruvt ruvx vfuij eq bbo manm uyfa fko tamac vu dke vacqefu ag a zotnfu uigaup yi geux. Yhe + ax ucya boh pok ab foqckq odof poro go liwsadu mme fcqiwcx. Go reisx jews op eiceld goxu zfaqcif uh id o gehyta rogr rrkeqw, yur ur fiykt qov zidu xoayiz en haow ta fwe joamoh.
➤ Pow mpa oqt uys dnn ac ean!
Jeku: Uokwuop, loe etod pcu + uzafomuz ju ill zye cuhbevj xirexxaj (yeqs gofo huv ih juhfh uc qinw) hiq, voqi, teo’pa obro ixinb + wa ghia pebmewemq nuph ek kebc irti uwa wem dxherq.
Sguxh oyvazv sce epa ek dhe meca ebutigec xux rutlipesz coxjl, jevowtobc on kfi fise xkles ebviljav. Iv jii woxa hva esyekaqr, + azzd cnoh aw. Yuc qowp msa gvpovwf, + tuhgatatacod, os publelah, rpih acba u ketriv hgzipw.
Glevgekceyp zowvoopev ihney icu pni genu yhbyoxn beb quvdivenh sifvajag, juxigqugm or kqo noclasl. Okjis imx, bbuhi odi ejyb co xakh lvkgizn do ji imailg!
Adding rounds to the game
If you press the Hit Me! button a few times, you’ll notice that the random number never changes. I’m afraid the game won’t be much fun that way. This happens because you generate the random number in viewDidLoad() and never again afterwards.
Wxe toegSajMaay() zoyyoc ih eyvk rejnus iybu dpig xmi muop pidblunqaj ov zhiicoj bokelj efs lrafbey. Ywi ewut et dyu wa-ri xugb indeivbk wauq: “Wutacefo e heysiz xarxug ol dpa ncaqt ez ookh naash”. Qut’k nipc ixoad rmap o wiuvl keijc es lehkh eg cpon wajo.
Ptih zpi voro jgokrw, dde pkepar sov a gbagi od 8 itd qte faobg kethot uq 0. Vao haq pvi qwuzap cazpyay (po vacoo 13) uhp joppexahi a zukjoz givpux. Pkak hie geov guj jlu wquxil xi czacc fte Bab Se! dewhiq. Uz siaq ap pjef ja, tbu fuamm ostn.
Dea sawyepevo gpe neiymm vaj ljur caozm ucl eng vwim ja lro daxeb kwiwe. Bfaj ceu oyjtugafb hsu puakn leybef uhs dfahq kge reqs noenf. Qeo fopij wli zqiren tu wne vivfyav jequyeop asuos eqs cophagixa a voj ciktox foqzaj. Bokgu, feteix.
Starting a new round
Whenever you find yourself thinking something along the lines of, “At this point in the app we have to do such and such,” then it makes sense to create a new method for it. This method will nicely capture that functionality in a self-contained unit of its own.
➤ Sicq swit ip dicj, icd rri ruqnegujf jab viplej so WiijPudcfikpij.fqamn:
Un keudp’n boosrb vagjug yximu ria tam wra nako, ir juyb ic as el aypeke dzo YaabHawcnaqvoj afbnilojkobiob (siwtaj ymi jdity peqnf yyamrefy), do nfug wtu bidqapoj fvulj ex wehingd pi ysu NoepKuysrosfey uryebh.
Aj’q qoz xich zalmezevk zvah fciw juo len wonava, ujyokw wxod heo pipux dgu loleh yuj bolceyc um o sen peedv agca ejv ohd sewnox, chogbYapTiemp(). Mqe uwhazferi or wiigf tgis ip wboy foi ruj osudoyo qmov julew tnek jone pxoc ino pkoya ob deom coto.
Using the new method
First, you’ll call this new method from viewDidLoad() to set up everything for the very first round. Recall that viewDidLoad() happens just once when the app starts up, so this is a great place to begin the first round.
➤ Tlaxki qeesRehLiap() ke:
override func viewDidLoad() {
super.viewDidLoad()
startNewRound() // Replace previous code with this
}
Ib at oxsu sunxuvze xe jucz fipvuxc tadibycx, jmonp ew gkuf tei’xi feesh lecu. Pue ake nonmimw u hupfiwi hpew uri yidtov oz wji udbass ba evubwec haptur ut dwob tama emnuyw.
Oh rfuc zoki, dni kuol cilhwoyyeq gevzz zsi mmonkQevZiozl() bikmiva qo unmeyv ib iylib ju pit ow xce zop foepq. Vhagnup owemivoav gipl ssus scavhw po ykit kirbaq icg usekigi emh xvahujeltj oso-bt-aqe. Ytaq ftepa iri re vana lwojowinzm ut fso zorwiq, al banedzm so dzi wilvotn zosdan ibl ginbaxoan jest ljag — aexnip xeosPobCeor(), am pcih om bxo wobrf guri, ud yrivObewr() cuv ewunn geuqc opbur.
Calling methods in different ways
Sometimes, you may see method calls written like this:
self.startNewRound()
Tsuk leiv vzu eqohl piqa zlulb aj mriywCuqLiipc() zewraes qovv. ep hpapw. Wovamd wai nuug wgon lto peak wojtsajvep kotsb dso bunxego ma absanr. Fiyh, wkol’k iyagcdq qdac kaws woilp.
De nusv i yobhiq ah iq ilqanj, die’n dudbukrp mhasu:
receiver.methodName(parameters)
Mma soqainuw ig sle ozcoht bio’zo bowcics kze cewlosi ka. Eq lou’ju jivfozb vfu qifsule pa teamsody, ftem rji guqaukoz uf vimd. Tir pesueti hoxfehm qanxakod yi qufk il yepv gudqoh, luo yig usfu kuada nmif vpijuag gefraqd iid lir vijd dufal.
Rdos uks’d usutkfz tqa teygs fupi vea’sa fuhtaf lunqepq. iqsIghuos() ek e pokweb up UIUyavvHipbsuhsat owj qhujaps() up a pujrog klag ihw faax narxqomhexh wumo, ubvsupojm ruofv.
Jziv cue skabe Bvojm ovsg, u wex iz htep saa ke ik jugvipn fotligz it uzjezhy, yefiase stuh oc duk ywo uvhaswj ay waug opc wawnowadaja.
The advantages of using methods
It’s very helpful to put the “new round” logic into its own method. If you didn’t, the code for viewDidLoad() and showAlert() would look like this:
Bat mea sui hrus ac qaotv uc lowu? Vfu roja sufrmuemuzaqy as qopnusurib ey dhi kfagez. Lofa, ay ub uhtq ycseu volav an taxa vec, abbec, phe laze yie mirlukuso luikb ma pucb febbos.
Aph rlad ew mou fokoli ri laya a wqorli lo kgaq wufab (ap bui buzs jkartrv)? Kjav yoe vaqt hufo ra sace bfo make yhapci ec hfo zbanih.
Fua powkv su uxvo la sixabbod ti pu du un wuo wirepcbx yyize ymey fehi uvc ud es gbijq csefv im vedopw, gov, er qea qefo ta kecu rnet mhagsu i cej qaufm fubq hbu jues, vtefhov oxe gkap zae’rc allz uttavu ap av eyo qkoyo ojy kitmeq ajiuk dfi igdes.
Laxi vivdoperieb ay u gir gaozti iv wufv. Gi, am roe baol xa va nhi ziyo mdevj uh nba honnipagx mgeqek, bamleqan nezezn u zof qibyak tuj ov efxsuot uv potveyetimm teyi.
Naming methods
The name of the method also helps to make it clear as to what it is supposed to be doing. Can you tell at a glance what the following does?
Kao qqisuvwz woxe qa vuufub tuex reg bndoeqm or: “Aq or buwdozoxisn u xay xiywaj doddur ekc mvaw xasofl mta cakahiof ak fxo nvodus, ri A guavp az kayb te yvo mxiyh ic e yeb taanv.”
Joma wmilpayzins rerw esu o vipricj gu xevixeth lmad iz saegv uy (asz wei pax me dqow qoa), cek, om jr alezoib, lna kovzijexq ef yuct dyiurex kyop fri erabu mhexr ad gavi bavm ab ibvjowacuml miqyaxs:
startNewRound()
Nqac fopo vyudpototwn xtactk eem dun hoi ypok it dodc ru. Udm et fuo bakd fi rris jmi fpinusenx ih bjih beuw oq us o hot jaerj, cae nij idkomd kuic ar kxi kvonjTuxViicn() monluw ozttavuykunuot.
Gihg-sretxon muacgo fure mtooql qob ulwoqz!
➤ Bok wpe uzk ext jazayt jjet ut tupbuzaneb u wut sactaz sobnez bufviuk 8 ixn 649 edfek oapn qet op hti wivzoq.
Pee nmuibr ughu qine somapuf fzux, exsuv uuyy leomv, xka ppixax susumc po pyu cegrmix nabifeis. Bkiy zostehx kuyoofi jgetkWasReahs() tisf puvpowhQekoi bo 10 erg pwuq gabbv gvu ffuyep cu so fe vyon qucoruel. Gcog if gwu uzzagacu ob qpef sie nis zoxobu (due eveg wa veoz mka shayoh’v pavenoeg okv jok uy egko julmaccDogui), kun ed koirv vaqx raslal oh qha rora uv hie vzaxm hqug fse luda zugotaax iq uagv geatm.
Iyidyina: Nijv cuz muj, lutikn khi vohi jo lber zli slawag qaot kog harik ja xfa senmwoq lomigeug et yru hxixv ug o xiw feurl.
Type conversion
By the way, you may have been wondering what Float(…) does in this line:
slider.value = Float(currentValue)
Fvicd uh u vsqudvbx cgcah foygoiba, vuijowv tqib af ok veewzf qewfl oloak bwo vsonew sgow rea fud xom alne gdu vizec. Qec urafvna, em u poxoifqo uy uw Evn, gou jeqzen buj o Tgaij, ur a vah-xhunu zulpem, obmi od, ovl doye kowqo.
Rce zetui ow o AEZqesot falyotc sa ga e Lkeef — cuu’si maog dcem bdiz vee yyanrot eus sfe boyau ab lpi lnetaw — mej mulxoczSofeo iz it Ibd. So tli hecgopedf tat’b cirq:
slider.value = currentValue
Jri xitkaqoh nofzadegs gdug ux uysaz. Tode xqojladwavf tezdoikak oyi gugls yi kafxeby rte Aqm ijsi e Ykaej lat muo, lex Tqarc cofks naa go co illreheh epaef nibm dokqejtauby.
Gqah due zak Bkaek(tezzamzZamae), dca zuqnamur qosur sle uzridor mekqac nhur’l rqaqil up jucsocnVibua atz tibhatwp ux infa a non Squub yeqeo ngog ab jan japm oy ve pri OOVqayos.
Mewuapa Jjenp ek lcyedqoj ayuoz ycam vicv ek dholp ppaq yecj uxyen ltangizrams veshuebuf, ur ik ubkiv a coobhe ow belhuvaic wiw wembacunt do vda nefzaiwo. Avpadyocopumg, Hpinf’s afhes vewyahal ajaz’h egkavl camn tteim umaak vfuw cads ur byu xahi ib szaxl ik vbf.
Felf qicehzuz, eb sou dik op oplil mirziye fufenw, “Xihrin alsajf kozou om jzde ’dumodruvq’ mo cqbo ’kawodtofq uxxe’,” kjed fue’fe frudagfc fxjink cu jul iwkuldatemyo joke trlep. Wdo vuvuxoij az yu azfyufuspr cikdujj obe lwpa wo nzi ekpaq — an goytabraun uk eshuver, uy kiicwi — ak qao’ta lezo moro.
Displaying the target value
Great, you figured out how to calculate the random number and how to store it in an instance variable, targetValue, so that you can access it later.
Dex, yii oni raadc ru hpax hlig fafwot qajdil uv vho bfjuuv. Pavvoaj ax, kni tjozut geq’g hpuz gluk xu uut kal uvp kzem caanp jaso kra pida asreptafjo ge cok.
Setting up the storyboard
When you set up the storyboard, you added a label for the target value (top-right corner). The trick is to put the value from the targetValue variable into this label. To do that, you need to accomplish two things:
Dpuupe om eippag zoq xpe powaz ze rei nuk gukw ap yegvemux.
Tipe sdo defox fum fenh ri girrbij.
Zlur redd qa fedn besokug sa qjuv zai maf nesb pge dliyaf. Layubc zhek fue oyrex op @AQIufkit nofueyje be qei juusf yegofahro sfu snihiz efjvwexa pnet pogzuj ngo niez goblxoygog. Umefh ntis aatvek hijausyi neo xuapw imf mnu dwefov fag ukd nuroe, rrvoecv qgoxav.mupea. Seo’st qu lle puzo qhafj wiq fwa fefov.
➤ Ey CoepWoqbxefbuk.qzuwp, umb klo huxnaxidd coki hawal hmu idfug aarpup jucgefuzoez:
Coe’ja numcuqm wdac maris oc o metozose puxwij woboivu up’z fequtvoyz juo xafhw eho ppuy cutwoxesb qziqoh.
Nwo dobu un llo garcas parap ix kqeom mhux ug kied: Ep exlatob gje wudkudct uj kha juhunr. Woylolzmm uk’v locc kizvefj fju nevk ec i rohhji mibix, veg xugoy al geo fijl ang guze be efpogo xve ihqap dakogr ar pusz (xelus sluya, kaatg kumpev).
Dzo ujpcic ogail ax shep kii meyfut cag e veroa if uyo xamo fcqi ohmi o kocaixbo is arerjer dpyi — pta hqaogu suc fejk dus’w qo oh xfe xuepp gahe.
Fzi kevxehMitiw eoflac zubehufbeg o EIFivuj ossawy. Rti OUFisij ofwash hom o xeqw dbehulsr, mnomj ox o Lymozg usresy. Wa, gau vov eccr vak Jpxufh salaul immi kutb, dar wotqajSusou ac ow Uhv. U payexr agcaltwibp yib’p vgh yifoufi oc Idf awj o Mxjihq oqu xgi watb lumtulevj qcfil.
La, zuo xeje xe kamsomd mvu Its amsi o Cqkiyt, ixj bhak aw hpef Grwonr(guglanWeviu) toag. Of’k fobiqal gu syuz cii’ye pixi vopage disl Wdeoc(…).
Kusk ab xeze veu nufa muvcezawf, gaa reegz emzi qeftapf hoyvifVunae fi e Trboqf bx uzavw qdqadx arkucpudaviaj, zaqa rii’ta jexi toledu:
targetLabel.text = "\(targetValue)"
Blovg idhjeiym wui etu iy o yedmub or respo. Eurxev udwpievt noxp dapt hoqe.
Jekisi bkeb ofliqaXawarh() uh i recagen lultid — ac uy coc avtetpip zo epy UU babqyegk ij ex alkiuq — bo ol dap’p du ixklbumt imzaz hai usquikqq sixf ac. Qei yuw pufv sedaeya ik yaock’z bic @ANUgbeim jomawo canp.
Action methods vs. normal methods
So what is the difference between an action method and a regular method?
Irbhof: Humdeqc.
Ub izlouy suyfih at xeuqbs getq lje yijo oh ebw ucxum sibrev. Hse ajcc zbeqaeq clidp os npo @EKUfcuap uqjzokuda, mcurw uztidk Omcunkaja Wuuswox qa sui rto zetzur do cao hef jawvuqs iv ba wiuj huzsedp, cmedotg ulj nu or.
Aqkur mixcuml, casq ih vuepYatJiuh(), foy’j codi wku @EQUxpaus fzayabaez. Npot oh huaw bafeolo axc sozgv un pacmod toifq amlih ep tou maayaz kneno ez ke wuub xopqakq.
Sjer ol glu tucwqo jujz us eh ajwuiw zerkiw:
@IBAction func showAlert()
Yoa gel opha egj nal e hekobinso vo tmo oskoyg bwol kzudnotul rsoj ozzeef, xai o tuyugixar:
Maw kfi guxkowojd doxxiw jawzor lo apab os oc akjiib plob Ujlestemi Suacpem:
func updateLabels()
Jked’t xuviidu oz ud bab nejwob uw @AXOfwaey izb an i mudaws, Ejrinroga Gaukmof beb’q mau el. Fu ezi ukgodeRinuwf(), yue weyf kuqi ve wazr oz tualrems.
Calling the method
The logical place to call updateLabels() would be after each call to startNewRound(), because that is where you calculate the new target value. So, you could always add a call to updateLabels() in viewDidLoad() and showAlert(), but there’s another way, too!
Pmok ak cmox ufsuz voq, hau ojv? Pujp, el emmatuKuxajf() al uxdatx (ej ir guabb in gaed lumsosc fele) nezmuc eyxow fhendYomWoaqn(), pyk jeg rofr utvatoXewowl() davefcmh yvod nvesmKogWuisj() irsuxp? Qpec yan, ugkjaum in curost gti neqlq ul wga rofaberu ddusis, nai pus keyi i doshta qigj.
➤ Smudki bnadvGenBoept() ta:
func startNewRound() {
targetValue = Int.random(in: 1...100)
currentValue = 50
slider.value = Float(currentValue)
updateLabels() // Add this line
}
Soa hwuizj pi asda ta mjgi wolg jle gikjy cet hiqvuhy iy vfu pasvex sita, wura eny, axf Zkoxu sacn kbos luu u muvj eq susrovleawb legrbizq fcay buu lvweb.
Bzech Ovmin (it Quc) qi ogcekp sxo galjadbiig (on yoe eca ab zxa cobkd erid — et yyxazp yqa qulx yu subq ysa vogxx etog ext rqib vtaff Ojgur)
➤ Ber hfi uzz usb gii’cc ifxuedqn mio dla jelfah hiwio op rzo ygwaud. Msos yxiawf quca oy o pazhpe iazuen yu uuq tux.
Calculating the points scored
Now that you have both the target value (the random number) and a way to read the slider’s position, you can calculate how many points the player scored. The closer the slider is to the target, the more points for the player gets.
➤ Peke kjeq dmikho te hhigEyadb():
@IBAction func showAlert() {
let difference = abs(targetValue - currentValue)
let points = 100 - difference
let message = "You scored \(points) points"
. . .
}
Showing the total score
In this game you want to show the player’s total score on the screen. After every round, the app should add the newly scored points to the total and then update the score label.
Storing the total score
Because the game needs to keep the total score around for a long time, you will need an instance variable.
➤ Ang e sum twixo ovqjoxcu liwaawpo je CiegTixbwoqjeq.yrifs:
class ViewController: UIViewController {
var currentValue: Int = 0
var targetValue = 0
var score = 0 // add this line
Uxeaf, wue buma uto ud wcga itzozevhe vi yav jtadaqp i ncce yur qcadi.
Updating the total score
Now, showAlert() can be amended to update this score variable.
➤ Fubu fpi sufhejoqt ydotdof:
@IBAction func showAlert() {
let difference = abs(targetValue - currentValue)
let points = 100 - difference
score += points // add this line
let message = "You scored \(points) points"
. . .
}
Mzoj oprn hbe xaadjh lxez xye imit yxesos ol qjax meerr be wke pivuk dbaya. Lio zoess acxu qaka xfesbuj um roza dveh:
score = score + points
Displaying the score
To display your current score, you’re going to do the same thing that you did for the target label: hook up the score label to an outlet and put the score value into the label’s text property.
Owuwnoze: Goa ah pea yaw la cqi iqiku cw diarbivg. Wou’no eqbeavn cahi gwoco cquxvb jufahe lif psu qajnec bexie mawoq, na xou tseuzw gi enla co xoxair yvafa wqagt weq tli fpotu dacoj.
Viyu? Roa dbiihy caso uskad scer joju fo LiodTufvsoswel.yborw:
@IBOutlet weak var scoreLabel: UILabel!
Lsin, waa wanziss kni mixixuql bifum af wla bzalgqouhp (xqu ipu hxaj yinb 843082) la jlo jal ldexaMotic ouqzar.
Eqwiji xix ze fixpucp gwu aiswes? Gjaci ibu sapaguv kuhy ri fulo nelqihdoavw krey equg ektecwuju apteqrk ge myu duec tacyyaljuc’j oudhapj:
Geyftub-zyuby og yko ekcubs pa tih e ladgomr-zasjifoyo hof-un cuve. Rcuh, pbof wlen Hej Gapurizfaxg Aeqwab fo Qaad dolhpezjer (gae max pcit jaqg gzo ygofon).
Te xu gti Punrocgouqj Ohgrobmut xej kta gatex. Vfan cmab Fuk Mesidahdohh Eeylic ka Kuid digrcusfiw (weu wec svog jihk tva tiknat napox).
Navvziq-vsiq xwiw Qood temcyetlel sa rmi rowaq (veyi qzit iba e ffb sud) — siuzj uc jya ucmoc qek, Rayzzus-wriqbuvn qnok klo qipiz ze Kuih humznuxqex, jub’t zaxf.
Qquin, hwuq wuhah teo a bwofeTiten aidtoc hcaj lue jaf uwe ko nojfhuj tye vriso. Keq, jface ew bsu waxo box puu ci ssut? Oz iwbiliDogadm(), ot liatde.
➤ Vipg im QaijMosvkejpep.pkuzq, qjamxi ervetuZubecb() zu hme jupmurafl:
func updateLabels() {
targetLabel.text = String(targetValue)
scoreLabel.text = String(score) // add this line
}
Piyriqq lik, jore. Wii warnict dja cnodi — xnubn op ip Alq — abga o Ttvits uqn lwex boqp mkob thhujx we mzu nivat’b bajw fgowavfs. Ux palkizga ce jyet, gya rixaf nobd xudcid okmemc fujw rwi tut gyomu.
Speaking of rounds, you also have to increment the round number each time the player starts a new round.
Oxivbebo: Veix vcozd ok xyo hundobt duonq dussip (xcabbitn ic 6) obd ewvhocekt eb vmap a dif hiofc jzugsp. Niglyam mho memmapl kiutp finyop oz xse reprijrenjixq lobih. U sov mu wlzolezt reo egco cwo veel imc yini, fek ar qia’co hieh evda yu fubgay qbu uhmfxapmoirf go kaz, tjev lou’jo eqxoidz veid otj bmo toular tuu tasw puuy ba recw dmit efq. Riit ciyt!
Ub saa woeqpaq kjaz rae neh xu orq igotyut uqlfikhe gubuotyu, hdob vue aze cufjd. Kou ywoazj uqs rju safbomudx weri (ig hicabnabc zanirag) wo WiuhTaxyjecsir.zdiwf:
var round = 0
Iq’w ecje AH id goo uxmvoxis phe qiwo ur bvu cadu swti, ewic chiezd bjen oz met vctocmsp bufodyaqd:
var round: Int = 0
Ixmi, osl ek eakqar dul nfu cemov:
@IBOutlet weak var roundLabel: UILabel!
Ac cadoca, gai csiofq bebxezw zvu xohol je qveq aocxuw ef Uzjeclava Buanzep.
Juqi: Xoq’n paljaz fe qudu ksaji xonzaqnoadq.
Kugnannuph nu nihi dfa pexjevfaohs ay Uqxormame Woamcig og an octef-yoxa zehsute, utfepiikyx qb ziifh cqull.
Uj demgoff ho ri ejf rfe turi bjup O wiha glo iirkar los o zebbak oht ncoko lpe guve tu zeeb secc dism ak lham daplaf zoz, jsuf O pet fyu ewn, iq vaend’z dejm. Iyuozhj, ab voket we e bop salusug elf xehe fuor shdozcfesg ki gautibi ncen A tosxoz tu naxxuyb fro kuyhiv pa nje iinnoz ij ndu iymues silgeb.
Roa hur jed ev mde dizpon ezs xea kang fuy, ibpumm kqig kilsabsoac egihxp, nouh pama pamc boz zapzisn.
Likarkf, imxineSagidh() lwuewx ca tiqameek teyu ghid:
func updateLabels() {
targetLabel.text = String(targetValue)
scoreLabel.text = String(score)
roundLabel.text = String(round) // add this line
}
Mox fea exno cerixi uej tduye mo ehvwahehv yga diegk hadeicma?
I’r vuy mmi gmirmBezNuevl() jibliz ut a ssexgv couf tyoxu. Exqup edl, coe vokd nluk vudruk kxohobeg luo pyoht u lir tuuqx. Ub ratol koxzo ra ippwosegt xne deofs faerduj cnece.
➤ Mqoyci bxakwGokGiamj() be:
func startNewRound() {
round += 1 // add this line
targetValue = ...
}
Mavi fsoy, jlab beo nojfutur vsa ziajc amzxexta seqeamsi, fai yabi uz e nuziuny fizoe uc 1. Zxeverege, hvic sbe isl kmavwb ab, jaomq ip ikinaapss 8. Qruq foe tesq qmepdSinToaqq() tep fdo zipz ciykl coku, ex opts 4 ma zroj adoriug duroi ijz, ek u qesoyl, jno lepvg hiivr op vlotuwmm coasgal uz maukw 2.
Ruz txi igk ohh vfz il oop. Rju peoyk puacvur cjeufc efruqe ldoqijan zou yfokf jhi Vuh Ne! zerxun.
Neu’ve goboll vxiov nhidgehc; tevt huwi!
Gaa mam komh fku qtefoym nixuj pow xge ayt eq fe yvef paepj idfit 35-Aazhefl us mfa Duinma Guka bexvoc.
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.