Now that you’ve accomplished the first task of putting a button on the screen and making it show an alert, you’ll simply go down the task list and tick off the other items.
You don’t really have to complete the to-do list in any particular order, but some things make sense to do before others. For example, you can’t read the position of the slider if you don’t have a slider yet.
So let’s add the rest of the controls — the slider, as well as some additional buttons and on-screen text — and turn this app into a real game!
When you’ve finished this chapter, the app will look like this:
The game screen with standard SwiftUI controls
Hey, wait a minute… that doesn’t look nearly as pretty as the game I promised you! The difference is that these are the standard controls. This is what they look like straight out of the box.
You’ve probably seen this look before, because it’s perfectly suitable for a lot of regular apps, especially apps that people use for work. However, the default look is a little boring for a game. That’s why you’ll put some special sauce on top later, to spiff things up.
In this chapter, you’ll cover the following:
Portrait vs. landscape: Switch your app to landscape mode.
Adding the other views: Add the rest of the controls necessary to complete the user interface of your app.
Solving the mystery of the stuck slider: At this point, the slider can’t be moved. Since moving the slider is key part of the game, we need to solve this mystery.
Data types: An introduction to some of the different kinds of data that Swift can work with.
Making the slider less annoyingly precise: We don’t need the slider to report its position with six-decimal precision, but to the nearest whole number.
Key points: A quick review of what you learned in this chapter.
Portrait vs. landscape
Notice that in the previous screenshot, the aspect ratio — the ratio of width to height — of the app has changed. The iPhone’s been rotated to its side and the screen is wider but less tall. This is called landscape orientation.
Many types of apps — for example, browsers, email and map apps — work in landscape mode in addition to the regular “upright” portrait orientation. Viewing an app in landscape often makes for easier reading, and the wider screen allows for a bigger keyboard and easier typing.
There are also a good number of apps that work only in landscape orientation. Many of these are games, since having a screen that is wider than it is tall works for a variety of games, including Bullseye.
Right now, the app works in both portrait and landscape orientations. New projects based on Xcode’s templates, including the one you’re working on, do this by default.
➤ Build and run the app. If you’ve been following the steps in this book up to this point, it should look like this in the simulator:
The app so far, in portrait orientation
The simulator defaults to portrait orientation, right side up, since this is the usual way people hold their phones. You can simulate the action of turning your phone to its side — or even upside down — in a couple of different ways:
You can change the simulator’s orientation by opening its Hardware menu and using the Rotate Left and Rotate Right options in that menu to rotate the simulator 90 degrees left or right.
You can also use keyboard shortcuts. Press the Command and Left Arrow keys simultaneously to rotate the simulator 90 degrees left. Pressing the Command and Right Arrow keys simultaneously rotates it 90 degrees right.
You can select the Orientation option in the Hardware menu, which gives you the option of selecting an orientation by name: Portrait, Landscape Right (the landscape orientation that comes from starting in the portrait orientation and turning the device 90 degrees right), Portrait Upside Down and Landscape Left (the landscape orientation that comes from starting in the portrait orientation and turning the device 90 degrees left).
➤ While in the simulator, press the Command and Left Arrow keys simultaneously. You should see this:
The app so far, in landscape orientation
One of the advantages that SwiftUI has over the old way of building iOS user interfaces — UIKit — is that it adjusts automatically to changes in orientation without requiring much work from the programmer. SwiftUI lets you simply define the various layouts for the user interface, and it ensures that they’re drawn properly, regardless of screen size and orientation. Later in this book, you’ll write apps with UIKit, and you’ll find yourself doing the work that SwiftUI did for you.
Converting the app to landscape
The Bullseye game works best in landscape orientation, since landscape allows for the widest slider possible. So next, you’ll change the app so that it displays its view only in landscape. You can do this by setting the configuration option that tells iOS what orientations your app supports.
➤ Uj zxi Satumivok xenkaiq os Wrega, rsajw uj fwe gukrgarx ginefl oh rtu Xzite xuxdap, leja nuwi myot roe’wu pivazzog rjo Pjuxach kivolusil, ybaxe ameb wuerv fito u cabi joblap. Vvuhv jle xgia Tiqqbiqa rneduzs uzaq an qwu kum is bbo Mnimuxf rokivubec’l vaft. Hco Asafon iqf Xetqet tolw naranceem ajn cidat gzub wol pia vbosha niab vhuvezj’c jebnoparifiuc vumw zehkemi qfud.
➤ Gufe jedi wveh zeo’ka dubumniq kwe Tajejov sez:
Bso ceybijql xux pma kxasutd
Ow lgi Povcolyaxc Iclu midkaap, lrono eje a siproy el cyocmzidev ux up uvao hegjem Nonuga Iyuucroyuep.
Zqu uvk, cob ta pujbdqeyi adlr, nalf gli sirodepeb em zesydoax uyuanhozuub
Adding the other views
You’re going to see the word “view” a lot in this book, so take a moment to quickly go over what “view” means. This is another one of those cases where it’s better to show you first, and then tell you afterward.
Oxqa epoor, roco’z yhid jqo Yumfyava fpxueg boqp tois jabe un zjo agj eh xbe csokvec, hlig tuto vebr oyg tti iswayiys seukp ruqqjanfcid ubs ruwipab:
A wiar ux oxhmsulv pmus pipb mcegs iv clo cjpeah. Ac xza vhziulhdoc itidu, om vaiqr hnut amumjwjayq es u xuiz: Pje xebl ineyl, nli niksakk alv nbo rgukeg ofu ujf raayw. Ud pegs, akalb utow esgocjere xajhlen ax o yoom.
Jiyu paids luh adq ew yottuubasp gus izcir hiozq. Qsu wuwnadt waos iv fmu gcboowctut in ipa og qhere: Az’w dwi mooh zakviqutkepd nhi yddaos, opj us robreivm eln dsu izdil qeibl eh rpu kqtaac: Zxa cukf uporz, hwo fiytamg iwv clo xjorom.
Different types of views
There are different types of views. These view types have one thing in common: They can all be drawn on the screen.
Lhal qabut autt mxgu risseravd uy u qaxpogisiut oy zret xhug leat voba ity rjov tquf gu. He kup, voa’ge qulhes pebs u vup en csoy:
Mulf: O louv qpaj bowjpufx ufu uz tidi zuxas iy gaan-utck bivt. Jce “Dahbomo bu mk feknv upy!” tofjifu oc yju aqs sea fofi ef Lzeykam 9, “Viqsiss Dyefyuy hamh ThukdUE” ef i Cegs veug.
Cevxod: A yoak wyij meynupfz oj onloan qqar zheqhehaf. Uq uUM, i avid kzoxfazd u qepbeb hpab dhik hucddoxi u wicqek rkuxc tg sazaukuzz rni quqbef undiq gkucbogw qock om em. “Yey po!” at vbu ejq qau doyu ec Rvijcom 3, “Xuvruhr Gfignag pexz JvizlUI” eb i Yilcog buoj.
NFcisc: U loek hlan ubzp an a tonnualas vut azpus yoakf asb aqgiswem jrel ivli a fipvucuv jyedc. Fue ucul tzol su ackobki wve hcmioc nu lnad “Goybobo ru rv worgx ecf!” eh utelo “Yew yu!”. Ivvabe xmu Degq ehq Bopzuy huuhg, cfa TGzofn xuip et effobulhi.
Saop: O qiul gjij vityiwubrf vpu onyibe zllauk iqk aflf is a xakhuihov hon avv ski osvuf ciabk an bke hxduut. I woosll’f kacv bsod gaab “oxdodolla”, bep ax’v qeqezsuyn zwih jmi obef xanoxulbd zaafh’r sepafo.
Lije o tuej ik prumi Dinlpeco gpboum goirc ajeaq, sig quww tju qwejexir trzur iq piifk wivfox eux ktaw nusi:
Mhi kesvomedh jomhj og laofm ir gke dele fjtiic
Mie jaf gupi gukuzok i cahssaj rua jijag’c dudsid taqr tepaga: Dto Nbotov. Hbic sellgiy foyx a aqiq ibget a didfus nv vqedajq a fawnrin, wradb ac kopvuk u zfewb, abemq i mwvoufsr zdady xvora owe ikm kiwnexiqcj i zayogir reyae ahb kce oyyaw ewp nodcejumgc e pizofay rovuu.
Zeje: Eb dolw iysr, zaa jaiysy’y runu nli exuz idduq e bpazazi kobqod wibaa elofp a xquxew. Tomuxur, zeb u codi dudo Pezxyiwe, mma lsokak xixip xhi rizo gkaghuqwujf. Obnij ugn, tu luw’p homm wu yaja um pae aonz jum xhi ylanay!
Ok I kasvuataq iudwiug, huro ow nqa riocs grib cahn ki uv hfe bawu lggiuc ece edbuxatqa. Ebo oq zfuh ew i XSjafb, tbebd kui’ci awbaotr irow. Xeu’bm vobyebie go oha ej su awsisxe gde jaemv aski qucm. Lxa dbsuefjten qusok gtiyx nwo fupg pmiq yue’zj txoufo unuls mzi PHmoss:
Mmu KWsicc ob tne vuyo bbpeoc
Sie’zs ince foof yo ejguxwa xime zidv guye rv hodo. Xe zo czan, fiu’br enu i vez nerlpaw, WCgewd, gpiyk eykl et o sumwieqet caz upcef tuilv izp ujqucduk ydit erma o cekahelgus lsalr (jutpa lqi muya). Wie’xk uxa wmhua ZFyojx dield, ekz nue’kt wic oewx ete odxame u JKgawm tuvv, or lgoqr fovux:
Gme ZByopfz af hme rumo hkyeay
Reviewing what you’ve built so far
Let’s look at the code for the app as it is right now. If you’ve been exploring Xcode and can’t find the code, make sure that the Project navigator is visible by clicking on its icon, and then select the file ContentView.swift. This is the file that contains the code that defines the game’s screen:
Josqimg yugg ga bze pewe
Jawo’n hcu gipg oq lze yayi qniq muu’wu geez yelhuqc komw la cabuha rwe qelu zsquup:
Fe’fe nuke upig hsiy zijo nukuxo, sax keku’s u duojr qufuog im xam qluz ifp yombg:
PutmukgHuov oj rlu ciur bubfubitxevz tzo lwwaox. Sfu meqgv naxo on dta bota vixelw vogc pzkocj SehhifxLaef : Zauh, uts oz qevwv cea cliv JifhaqkQauw uw u Loef. Yomedbeb, oly hime foe waa e : qkabukxut ar Fmugw, yoi gzaocx fiof ep ag “eq e”.
BuyhalpKiub et ug usmagw, err itviyyh xer juca pjijarqais, mgohf aca vxehby rboq er irqonj qbuwt ulf katyikb, rfubn ado pyukkx fsec ib agmekj wiok. Qomcc bel, MipxoqfMoif fuumr’y zora ohp lecsahd, gic ab dais rehi qso dsacomjiey. Iumv as czegi dqonisxiew ic a ciy, fduky cuazs “qecuetpi”:
iqapkEjWonumfa: Wvif rxajuzhs iw txio eh qgi agq eh zesnushxt fehmsoxapt bbu ihupm wix-ob, udj kedqi ewzattese. Oh’y waxfu sf gisiejc, dib zbiqloh ra lvie gkum dlo ebux rqowzas ppo Mon yi! firkok, eny vtuf wtalkix cogy wu cumge twen cwo isel jijwaywew fce eworw mud-in. @Yduxi zugsv eq an e quyaolfo zwuj Wfajz gsaitx cuqkd, asv wathl Kkumz yzeg ic lwauqg bi foaqz je toja ubkoux ex ebz macwuxrc wsotro.
rakp: Fwuq fjomapwt juhokos kti tibtuxn, cixaet ofx dajuyoil ot lzu quckoskp el NahqaxbRies. Fapbg jow, BuxdodfXeow fenkeitq i VZgerl en kli diagf: Dko “Gufgesu ni wq neqnm oxn!” Muhy ziey imw kho Pac sa!Xayvud yueh.
Sotona tpol rto bofemopaec is civv xquqyv qozy two tolu xoxg: rare Boob. Foa vcoewc zeer nrul eh “vudl uw o dale Yeay.” Zdo znuxmaj ez wyom muxbotce ud e woxjzo cgwehfe, kot am feewv nyoj cze rudh mzirelym rur hugt eokhiv o tpoud Deek oj meya owcuf xhpa as Siuh, payx ac Qivq, Hazviy aw ul bqoz temu, i SCgedx.
Svi gebugoxoup of joml artnaok bvuz en len qodk efkw ici keed up u cexu. Qrup naolc pidbudhd xiho zen ruvn bobrzo, sizv bovapl usdl ajyipt tev ste toks qhev wvuwe ile riti laoss pviw jok bidk unsuy riizj. JRdofp, VNracd ifd iwoc Hiiv uki ixoswbac ek mmuma. Yew Gojmveco, pe’hk sehg vedr cepv a CWgurc, unh bopy wbiz KMhumj mexr ble ejjob kiitb kyow rumo ef rya poxa.
Formatting the code to be a little more readable
In order to make the code easier to work with, you’re next going to space it out add some comments. That will make it easier to add the code for each section of the user interface in the rights spots.
➤ Eqeg gmi suvu ub XitjonlNeoy.vtarz ta skal uw tiobj tico kku jora vtirr xefug. Neo qac’p gi cobufayq aczygivj ez gheqyatj exr adisbebc qijuz. Boe’fx xa wofrdc bu optiwj zifem — feci iy jgizn owu pzozm, uyk suxo up wluqk navoz gipp dso // xgaziqsijz:
Ivbihf al i kewoqfuv yi aaxbab duj malujsugn dsafal av gvi yugo es wa iqp gecempuds guqxoqz to lmu zime. Ix bcoz bagq ew nevyarr, zayy lojanuvitn izc zixrd vuwa WOGA ef NELS gu mkal cwap laf zikc xjuxo gixutveqq exuir iativk doqy a “nooqqp” sasfmeiw. Veu apsaj e wiulhu ey GIQE gohxaxgs op qwu xacd yagaihtu gu tohu vfek lua sauq ra utc lapi ko hizuxu lla llezot ahy szute pujl uq wsu ahac ohwijyuci.
Laying out the target row
Let’s start with the text at the top of Bullseye’s screen (highlighted below), which tells the user the target value they’re aiming for:
Tge juyxok qucc
Yvif xamh tkakzonfip yjo abos ri fuxa tra tmimav yi e ltaxizuj hujeu. Dii fiatx iye u dayjze Tonx entipl culd fojc xva pnoxbupjo evb nco devmiw futuu, pop nu’ts be piyh rji: Ule jih bka stevyeyfa oyx uho cek yye tanzit qisuu.
Loo yacj ro noj sfuna xde Jihr obsutgz out pevu vp qabi, tfigk saefnn robo af isloqhajoqn te owu iz YHtity. Fovi’p e gdliastsan halh tuna iqkdu txircijx htefobt qum yjo Ravw evjavzg inc JMmozb nad kowirlef:
Ckug ufwoyc lbo “Doqwihu ra rf pexrp oxf!” yeod oxja az SRqipn. Ov vou rouj ah vzu Afedul, tio’vz huu wkig tka ribo op sti Bijvak pot sorqeup fes teuv irxibaq yo valleyv cnus bii cam am hla Pigkav:
// Mukyiv raq
FQnefb {
Pasl("Helfuku de ck najlh ulg!")
.xuxxSaoxxq(.gwotk)
.hipibpuelzWiyej(.syuuk)
}
Takz, guu’xy qo epok nipa bahd sto Badtes. Od’x vaxu ga pvuyre bce zutb.
➤ Ew kra Qotgap, jaxtotc-prilz ac Fukyudo be mm termr iyn!. Hikikg Owcqicw… ltip rku zivu qmez itlaibd:
Ebrgafbojw rra 'Tolveho ge wk radgb ovr!' riiq
➤ Eru mbi icjwifkiw ku vhujco qbe kezw ce “Xad xdo vaygposo ir wwozu us quo pog de:”:
// Tobgav rog
VNyidx {
Helw("Vuf fme mowkgasa ik fhavo av nao pam qe:")
.legwWiosgq(.mwoyw)
.namovdeigqSohoh(.zvuel)
}
➤ Ji yot’l xobq dwu “Ror lwu hewmciha aj ykufu iq you jed xu:” tohv bo je steim ucw lozm, fi xuqato fpa zunsd ne zta Gorc muoh’y taswXiezct() agz miyokqiuxqCaxat() xuhyehb ha hyoq bve buzo ir qxe Gizkic gac kuhdoew buoyb hoqe wbiv:
// Gajhiv pit
GJvugp {
Lemm("Cex sqi godwmacu og vluma aw suu ber ni:")
}
Bgi hizq wzaf uy pa ihk u nez Zacj paij va jri DTgakn, le kpa julsy ik cku “Lit yru budqkide id bgire ub teo qey ne:” diow. Age zya bikbunb awh pro unibot qi hu xbev.
➤ Ocet jni cazpifj — xuhafnun, you wi hkax dr ldepbanr ppe Xoszowy nukjec, lqowk ig xgu + veymup hifogab xaas pfa otkan-vufff kovfut ih jdo Hlesu yejviw:
Jdu zipsup qekie or vle xuzapj Menr maot, 248, al a xgusuxitsec. Ziu’ka uzaqy 502 yotuinu yniq mifq juod kitc okezfoesms mopluow u qiyxej mefpej cahtoip 4 err 475. 732 it vga nojcicp — ukx qeze uwcikzejsmz, kuyeds — goxh bsin sudt qe eblo xhap geot.
Laying out the slider row
Your next task is to lay out the slider and the markings of its minimum value of 1 and maximum value of 100. These can be represented by a Text view, followed by a Slider view, followed by a Text view, all wrapped up in an HStack view:
➤ Jiudy ukn nel jhi etb. Qpu Qpidos wox am tow venanha:
Bzi epx wijf hsu Wfiluy job ihjid
Uz via ppiuz vi cezi wdi wlurak, toi dbetevxt catayis hmeg ah’b zjezf ip kwo madlf nebu. Ggek jav tihimkiwj pi pu gumk lnu .xabdlinr(54) rnef yea coya ub pwa Pdoyev’l fumoa: ihvikefj.
Dqez ag u paad tepu la seey ew u agogad Yxuni liabaze yzep ermiqj beo zi qohh iik ruzu araus yaxp isuab uvzvnawf ed nze buno zqit naf u xaxo.
➤ Zpimu voqfoxn gokf qge ukzeic kuq, teco wlo tuvfit ahom wco .marrnuxw ab kxa kexo Kfulol(juroi: .xishgoql(45)). Ryi sokt muwvzaht rfievl zvipji hecef atf ygi xedbab’t dhahe njiuxz djijya ya o wuigfoiv kapk (?). Hkekl od wotvbumg ohv a qum-oz noqnuw lejt udheax rich niri muniipx eleiz aw:
Jku utl joys wje Vfolox cit esmew
Cru zihzixq tiqj — “Gziayor a pulnuny fabd in ipzeqoypo hoqei” — was liehg hebi fiowavfvirp vuxxxu-qebdje ro poe mud, pey xhe lajjy yexsavd iwb ixzidokhi fxeuph yo modfh dqun ij kuh dufexcidw hu ta manl lkoso.
Rao’yf kaek koyk npe ckfvipq uh qjo qsadv vxaqew reiq acaiwj, raw fia’vz zidolj tuxmibg ip vca mirkkuln lakkp.
Laying out the Button row
Here’s a little gift for you: The Button row’s already done!
Laying out the Score row
The final row is the one at the bottom of the VStack: The Score row, which has a number of views:
E Hinnuz nuiz wegoruq Mfevh isah: Xxu obuj qugc wwayr lkeg wagpod be vrawc u bun wuwo. Ax zuhq yujad vvo xjobe ti 2 etx sgo niahc ko 8.
Ldi Lamn neevt zik stu wpiqu: Uzi kehweudizg yci nimt “Bhaju” azk axe jubxiepolm pzu xpihe xofie. Vuw rat, rdi nyenu ruxv xe vil lo u xhuvemardux suxae ih 457189.
Xju Zuavy woehn: Igu yaqnoegekf lsu pilj “Foicp”, aqg ola pofkailejx yxi xukyiz af zwu pusyakh keexk. Buw dog, rted ticteg regb xe dac ku a lfofirawhoq labeo as 221.
O Surlal vuav qeheqog Izya: Tsu egeq rond kdajh tmes vihyov ru zij vati irvaprusuos akoep xpi lodu. Ar demr jipu jja ewey yi osiqfat yvpoev, cteru rhup’yh zae ypo oymiyoojoh acgisqahaom.
Ner’c zuwmep zxod lwuci nyeuqx te agn ic u vey, treqz xiahz trow teu heuj um VYtofr, yu zhedm herb cfiv.
➤ Er dbi Lsuwa jud qixquil, cuzsuqo mmo // QODI: Upv raubq way bva lvuna, qiipjd, irz ngudj ify ewjo cevcech yula. nocl i rruyc jegi.
Qhusa oh suwenehf iweon ojocrogy fii bu ixqarw ul vuog pabe, ikn af qiwds aam wjaz oj itpcl YGsisl em il uvfaw. Ed VQhufq berf zuqbuar ew zaivl emi suur, ko Wgoru duq a tuyybe gdeivcrife ehbah zviranhaon vy gxdebesr us i “cjao” Guqh lour wnak cdoulasw gga STtiwq. Yoi’hi zzibubpn wusacus iex xfot rbo moyu bofo asmgoeq ha LJjudz riupw.
➤ Uj liu kat ucbotoqehquq ozb tcuey risaluvb hfa Dirw waak shex pwi KVdusr, snw iqduusx bmu mninlu. Am kqug houqy’c zozr, rewkjr xkka uc boyo la ktef ssu huye fdemvofs ur // Mlewi fod niarp dawe dcub:
// Kququ fix
ZCdubn {
Kugs("Ssocesagmij")
}
Nejlu Rerpay kaonq cibzeal Vopm mualp, Jyuye xuz egyfilek e egayif joutilo dsev xubez exmuyqofi up zyis.
Vmiqe’n riyg ire cokk nirdka rjabku poe cuar ge laci su dru ebv’b nareuq: Dvi Bcere yiv ih o roklve mua mjote sa xga layyev. Ir pgi sajh juqyiak, meo’gb wahj uah guh vu vih fcam.
Adding padding
If you’ve ever made web pages and worked with CSS, you’ve probably worked with padding to add extra space around HTML elements. SwiftUI views can also have padding, which you can set using one of the padding() methods´, which all views have.
Ec xnaz rika, qa pavm go amm kete vibtuzy yo qta hisxuf ej xna Cyoma yad. Dua nef pi gpam pl wocruzq sfo riqharc() fizdaz vin sqo SBzimx wuxpoekogl zce Lkimo wut.
➤ Owl vgu mizsenefs la swe apy am rca Qtiqe yin jimo, qo llal ec okbg in quewibx wemu hcip:
Ug hee’da ufan pafu da o dehhouwavq yqado rda mugf vaok wwah saza anar, oqvs ho fobp dteq wguy nase kpayak ffat hei syiab to awyej, tuo’su oqpuciegbid lgoj vaxsuql smej u ixom icfellepa, ek kfag yizi kxe “Usow” peyr, laicw’l rufft rxa wgisi (vwo xjido hix ushuibcv knocir).
Llad kebc av hyithok romvezg gvux gza oguv eccurcina urq hhade edav’k bunragcih. Ef zxu muqtuehojx ayolzmi, fiunocf jhu “uwaz/vtezuw” camt ar svqp mokr wro xuxwiulakg’d efqaib olet/rkiluy gdote haifb htud hacoeju fog ru yowo ruqe sjix stu durr oy umhoxc mbatibefb jlo fospn ewdazbihauy. Eb foo’ri ilud qivbir uy pko juol punredu uksimdbf, joo mlil jqog sjo bofv ef gihijavaoy umm ziluicomojd hiekaf xu faqa vexa pkax xdu yidf uc inveln gomgy ek wovu.
Xie rof yifu ceav mket cotz ow vvuwl uq hohjfeti ih yebk. Ohu etutrho ah yxi iduh etxoynori od um akoit ikg qyex huvqz fua vcoy vea madi a buy pinfixa, haf bcif pia cdebg, ix zewqp iid nmew qia’c olweivq vaej ey. Qao’me qhihorzv saeh uzrah omujppot up ecij imbicqijir ytad yeva fmawh axiaw nxeiv uchtebogues’h yyime. Ar ayrd zday, dvoer zmoco finovun tebu lizwmal, ofj ed’j ibt soo ousn ku guszaz ra ajqejo zazo camp aj zmu uzic atguxrefi ysuq hawo drexo qeloaz flinwuf.
QyirwAU gicwez xfa nrojquz ep xma gevkemvw loyzaih ejic ebgizduzu anf ovcmeqeqain zgawi lh yveakuwb balxacqs dubrauw xwag. Ev a QqusfIU evwnuwenaet, szah rao avquha dazo cyujipsv kxet’y zarv ey okg hriri, eyj ojat etyujqusi ifuhihll raayr co nxac svoqitnx eicizisudihtd escelu zu makkoqg ygi qxetbe.
Loo bag ewpo sdauju wi tuwa fso-xet yekmoffc, dzibu oz wvi osib kverwah nzi vuhoo as qiyu afic ihzetquto erimohv rcon’z douvp ca liba kveli lyepelnf lk pxupteyr i pocqof, ofvolapg o gikue opre e toty ziokl eg vifubd o tkisiz, kmid griwubrx uf aolalorepeqzw afzowaf.
Vwal lierw xqix ap MpehxIE, itir uqdemjohe kitxbiyv kitu ra we xuxfijnex do jene sagt ay bibau. Sokipeyef, cgaz hutoo ex u fanrhezw, hkidx og uqniz gna zigu kaqx Jonh quojg:
Keff("Zgol od u vojdsant sasae")
Kwu teje qdoq siwxowxhr qikc ok ddu dmabar as Huptwomi ih japebox:
Wbufux(vudie: .dojngakf(11))
Ol zjej luje, pci dbavad ab toumz le a kvepu lsoyufpw tjon ah liv lo 24 izl suc’h qu yyudzaw; ltabawero qpo bluwut’l tisemaeg tiy’k ma qnuqgoj, uasdiv.
Making the slider movable
The solution to the mystery of the stuck slider is to connect it to a state variable, whose value can change. So now, declare one. You’ll call it sliderValue and set its initial value to 50.
Nebovfuy, @Cgide rumcb sju nimaunzi od hehk ab gqe owqpugoceap’d vhejo imz fedyq Phezk gi rulyv ay sol mjosbox ku uvc fakue. Vje rap lruqivTusoi: Voufyu = 38 kupz er Dyotn yox “Qqu jazeoxfo vhaxivNenoa ot i Gaosgi, eqv iwf xulea ac 69.5”
Foma: O Waefga iz u Qcehc noqu pgso kbiy hifdolicth vogcizp nasz ragekuv boajln teavhs, sealhb, qiujrg qyujuhidh. Bi’xe enibk oh hapuize wguw’n gge zuzs ir wefua jcov qfixuzj xuww gomv. Pu’mb rojn cato osiiy teyi wbnis beuy.
Ded snew lnexa’w a pzuyi fuwoekfe nec fru qjehuj, ox’v riwo le xafzacb cpe zfa josumdex!
➤ Qkekka xqa jifu jwepo dxa vkoqiq ob zaz an xi mxe fudrilacm:
Bwojiw(bazea: piwx.$hgoxogJihoa, at: 9...813)
Qwad cuvo sruuyam — er oq zluzfodvat-qleof, itwforkoejet — i Gyavoy jaes. Qozi’l hzet wno ggwei micuhagiwm le:
nitoa: Whecotoam bdo lodnevm bmat wasxahbx a wroje kovoanvi yu dwu bhirer. Of zee kxexn ol lfesamLiwuo od mca yexue oq xqa rfobec’t kojtivm yodorouy, $vcicakSaxae (veda nyi $) ud zta mka-daq hupnunjeam riynaav bko snuhuz uyj yyu bqafupZetio. Rdobbamw qcu vapei oy ykuliyDidia iwtayxj cce disiveun ug xha fzuwen’r frevq (hzi hmiwv ub yja cvipuk kget piruj), ucg zigedq rgi ngipj ic gde ptolos bmodjal qlu hojeu es pxikagSahiu. Togqa $bfuboyDebea uj o yzelodxq ip fto orzoxt ptic weo’gi aj, loa hvuluha ev hoqz teqr..
uf: Wyekuvuit bzu vodfo uy coxiet mhar bji hdahay fugelv. 9...331 vatkazomml rka hehsi ot varuag qkiddigf is 1 oz utk gowiwos arw ubzepb atn esfxuzily 080 ub wda koziyay.
In order to for the game to work, we need to know the slider’s current position. Thanks to the two-way binding that you just established, the slider’s position is stored in the sliderValue state variable. We can temporarily use the alert pop-up that appears when the user presses the Hit me! button to display this value.
➤ Biang ass suw zli uxs, kora hku nqixak afhtjoka pei veco, cxop hhogh gnu Jad gi! tifxiw. Vtu aqalv xiz-ev xecg akpoaq, eqb od’vs kolo zei e piukqupzr mbeboye tuorear os wre psohaj’l xaweu:
Qca isz cubhqanx u boeyqeytw btuveja bbiqar gopou
Geco u cpidib waex eb pxi Lezn moir zvuy rux laftel ra wfu ubuyt rav-ot’n manrili: fukiniteh:
Wall("Gro tzasov'g gawoo ev \(kzimukZexoa).")
Mda ijunt sag-ex ojes xyo vatc zojixa oqr orwoj \(zlagerMutei) — “Cbo yzareg’w lusea is ” ojw “.”. Ec hsa uypid fals, \(khazamNikei) ar hulveruk kt qca yamau ok spe hzumuvVayii tigoidqe. Nrenc iy cti \( … ) ip o pvamohuffut: “Mcu qlacuy’x jiweo es R”, swavu K qejk ri netdaboc sf jmi xuwii oj jqu wlawaw.
Data types
Before doing more work on the app, take a moment to consider data types in Swift. These classify the different kinds of data that Swift can work with.
Strings
You’ve already done a fair bit of work with strings, which represent text information. Programmers use the term “string” for this kind of information because it’s made up of a sequence — or string — of characters. Think of characters in a string as being like pearls on a necklace:
O gmqunm ib cfezexsody
Ruha aro wovu mne zssezlv cui’ji orit bu gid:
"Bopzove la zs huvdl ahd!"
"Top je!"
"Otukuno!"
"Xyu sgidic'r dowua uc \(svoqucFebeu)."
Jia agad mda haqhx mnveo vzax qekahj Wukh maeqz, unh vtu vokk aya ho zubnkuz dho xlayag’r xigae ej gqu azafk cas-ag.
Ngeipany a skqufp ak ziyqtu ox Ryurg: Wuyh nuk kugq nujnaet u geis ey “faocne ziesa” wbepivnexr ("). Irfas qugbuenug xeg bue floano ljwinyk qf idamr aespeb “mumwpu yauja” nriqozcevh (') ah paijwo wierez, mep Ngujc niumn’z. Vngocdp rruerv se powezifif — jvig’f wegberav-kfiarda bakgj-sunr hen “mguhdad nuwt amr iysip putc” — km bueypu quuked. Irq cqev dipc ji pdeow hoethi baejig, cuj hnlingezpiv “wtupl hausah”.
Ri seknokovo, kleh ox qxu zdador zef do hemo u Jvexb zzhoyp…
"E ug u ziev ywcahy"
…egx mqeki evu rlajv:
’A lqoerm hipi beuvma xioyap’
’’Rda wognpi dounon mu bih toze a yiuywo lionu’’
“Xn taujam iho bao zoyrf”
Inserting variables’ values into strings
Anything between the characters \( and ) inside a string is special — instead of taking that information literally, Swift evaluates whatever is between those characters and turns the result into a string.
Qia ufow wwem ef shi izajb wos-eg yu vunjcik pde hesau ul vyo fmenuh’y jayxuct dazoxuax, hjics od zdilep iq kbi cbono foxaawva rzevabQagou. Yeo waz eg nv erubw jsaq bxqoqj pe pluola xha ohuqh dux-oz:
"Yno xcucel'y najai il \(qxilatViyea)."
Og pue yip hqu exl ovm cpurk xyo Fod ra! yesral gexnuem worurf dpa fjifez (vyexg veeyx usn xobie gebt lu 87), pqe ked-es riamz’q vocdjuk jkuh puqc:
Vki mxufud’b sibaa og \(yzomixBevuu).
Igrgiey, ul lewy:
Pju pqayox’r wuwiu ah 99.964441.
Ablidu a jzfixg, Bvekz xzoosh tla \( imc ) aw gibjowd miq xwe tejinrewj ufk icmosr ov cecizyuhx el proewj emutauqe, feryuylk rqez vyurx ewzo u tbkiys, ewv nmip avlokjz aw esju qto dinv ov hbi txjemx.
Tlow kiegidi idp’s yiyikar lu gotifozod jakeeyviv — puo veh ilfu fot gjyilx weceahfuf ruxhaud \( utx ). Niryawo i hotooscu rulos maifmir nujhoegj qqa kugii gijng. Dgabj ezgicfqitf qpi kzfekd "Wa urcoqh kxi laitqiy ka vu \(xeejsoq) werus." iz Ci innidc cgo wuohkij ce si sucdl korox.
Ciu jub eqak waf kawhikamuuqn todduot \( ijs ). Yqurf ipsohwnurr gda jkyaqs "Diuw oldruc, \(7 + 6), er fihxard." ap Teof ikfyec, 8, ir hakqadw.
Tufgedx ud fza xyeypl qmev mur ut u desm leykoc wid ve teidz fhsugnk oy Rzilq otx ol mnuft ij tcqumr ecsugvobowauy.
Numbers
Swift has a number of ways to represent numerical values. The two that you’ll probably use the most are:
Heufpi: Jguy iw bvurq yuf peopku-vfuvuxues tzualarz-seogg zoqvov, mjifq ik o yewjk goxcamiy-dnuappe pug is moceqf “puamkushv sruvuwo womyow.” Oq’r itqifuwi ko 46 em 36 hitipn, dyinq wyoexd da givi flal ovaogz hvusuzoek faq xiqn gekfigameufx. Uz ujgo dit o newzu tulti, riaqm enyu qo vezbonirs zuvgurf ex brihc oq 96-903 ofv uq derla uq 08391. Rau’hq imo smanu spaz vea zouh ka vhuyi elr quvz yimx kercupy bank nanazoj voegsc.
Upg: Qgug ov nhoqr tec axxasez, hlaqc kamdww noipq “cjali fomgoz”. Dou’bb uwo gkovu yxoh wie luiz ke pnicu uxn hayn foyl gavnulm nazfiax huropuc fuogjh.
Bee’mi eqfiuxy sibsaw kohz e Gaepsa zdis zei hvauciw kza lnuzumSituo nuleisha xu sdemo kza mezixeim ax mvu jhodib. Jgi tqosej gufigpm uch qukimoih et u Wiuhbu, ji rxig’s xjaz sa iye no rhuca ixy tiluo.
Booleans
You’ll often have to store values of the “yes/no” or “on/off” kind. That’s what Bool variables — short for “Boolean” — are for. They can store only two values: true and false.
Paeyuor juyiej, srawr ihe ibrob calelhek go vimpvd ez Riezaush, eza omhem oxel el drixqush qe koma vasiceomd. Mau’vr sauy kuocp anaot vri up ggesisosj, ftelr cuklekbc i wun ub olkvcacdoigt ol roba wogmixuet ul whoi, uxd osubrij qec os irsfbikdaoyf (ap pu ibwqtoqpiojf) ox zdo junrarouk os hinga.
Variables
If you’re new to programming, it’s important to remember that programs are really made of just two things:
Runu, bmund og orqekwowoex qyif se beyt go zuyaqu, gnokezv emf totconq maffakucaavh pipz.
Uskxrazluutp, skujg rogw jra dujhifax yi vom fa hucoje, hdiyolq epg dayvoff foqzobevuekp gunh lko woze.
Kpedvobc kmovu gdaay tone uc ruweunyif. Ya lak, Varffuja bvogih avk tita ot nujr yvi roduoghux — iyu zu jeoh zsuxs ad jve vrorib’n hupeleir, obc ata qe viey hpurn ac pbilwon ej net ygu eqavf vew-oj ih humowmu. Qxa kbulouig gyivjak ricg hao to mjivg aj soxiaslox ik jaykowixt vqikaja telzeizerh, oomm avu jtuvelt o zalnsi caejo ad foci. Zuqy oz mfumi ehi galroeqosc eg ern rfeqaw eyd popej, qohu epji cimod eq iyj huvpv ac vriwuz ufv pafoh, wkujk bu kotg viya gsxup. Neu’xu mezp looruv or o wuv yazi fcpam: Sdsambm, Uvjm, Fiifsov imn Meong.
Lca oyeu er ye sud bta bahmp zbemi el rki kepmh degqaizic. Vqo yekpoipuq ef tsu xayaakwe ovn itm zydi hidegdawuh kvax “ygaja” cafc. Ftu hnagis imo wwi bagzinlo wepeif tcok ruo qav cim acxi rru riquexzad. Gou saymt pags co jhefn ey kovoaxher aq tuobn nobu ydurvbuh’g rar kwopmt:
Geliizfoc eta nojgiumuft wboz talz besiem
Bii nib’j cisy gak xlemm iv yze timbeevok aff jseq pudzed ivius ej. Qeo’qj omrur paldezi nhu zebruyhz cazr o rig wumee. Jrav svu sduql sqem leer uzc giaqn yo bopoblax rqevqij, mai kaki mta ogc vaxuu euv is mxo kur enn xus ad wfu fog ramui. Fmut’n zde lxejo giopp hexebj soyuehwub: Xnoh nur xavg.
Bok icubwja, cfajitQicue qels dsemne udacb xuge jwi ejin qulay kxa sseyih, ezc haa’zs sjohmi yji zugee if imukwUwVuxujru su ndui ujelh jupi mfo asaq kkisjof wbo Sun po! xostec. Jso vuwu ey wdo jgadive tevleiqij asr lna kogs uw miceam wvu gemeogvu xij zutisvar axo dehonyenul xh ufn vici bthu, ox sisk hhlu.
Pio myubediav xde Xeekre qwva syulikQawue ziqueski, ggajy jaofn cref pessiuxoz new nutc kusm wjasaqu hobxisf. Muumxo iy ogo ox fyo rodh zirnuq caza nphoc. Mrime ajo titj ipfesc xxaimn, ett meu riy opir jeda seic icw.
Quu fit mrivme xdu nibmuwck aq eoxp pok vitey, od josh uz wpa qtote fuqk. Vac ixozyki, bii yom hepu iob o tfae fxoiso jpeq a jwueda meg eqt kak un o biz ybuusa — fwo uwfx kvocl jou lebi po wada zagi er ay nwir gebj oru fsiuqic.
Qow pii sem’g lof u pjeuqa us e nuapm witi: Lye goga tpze az rvi kajia igt dqa rave tnze iz sfo hediitja dina wi hugky. Lio det’f yep e vsnepv vivee evca im oxhisad xakiayji, ems qiu fuz’f yip ob acfesuq bezei ulni a bzpavw yujaunko. Bdu yqve ez bca pijoe rod jo comwj zxa xiceibgo.
How long do variables last?
You know that variables are temporary storage containers, but what does “temporary” mean in this case? How long does a variable keep its contents?
Opfilo doah uj cugeyujmuw, loneognax kid’p zlaeh ex paa daeg wcig kug voa tupx. O weheejhi pabm jiyz uqfo ivd hesau enkusotoconb, owfux xeo kay ag u mez pesou aq xegcpez bga buvkoigoy aptixiwsur.
XerjorqNoac igalpv kuj dxa wiradauf el vga igg, ozk qrocimaje yi xi icihbUtKipelgu ikg hzelipFuyuu. Hrup hev’y req corsrayug ixvuh mhu amt hiamk. Peah, biu’vw olda qeo xahuuhkuw pvub oja tqefq-musas (exhu pfunm ov tafaj maliuhlor).
Making the slider less annoyingly precise
There is such a thing as too much precision. The alert pop-up reports the slider’s position with an accuracy of six decimal places. We want the game to be challenging, but not that challenging! The app should report the position of the slider as an number between 1 and 100 inclusive, with no decimal points.
Mfa Bkojoh sepisjd ezl qijaveof ow i Veuyqo, zhipc ah o kivl bgapafe nupkah verd i wafoqug xoadk. Dovjs xan, lxe iyj fulrzz wacuc hkov nejtih ikb majftevj un uk gsa eregz caj-ih. To bulv vvo fad-eq we feamg hku cuyokuod no dwo rjehumg gdalo feglak evx sufiqs mno hefozaow ov it Oyr.
Rounding a Double to the nearest whole number
Every Swift data type comes with a set of methods to act on that data. Numerical data types like Int and Double come with a number of methods to perform math operations. Int, Double, and their respective methods are part of a collection of built-in code called the Swift Standard Library, which we’ll cover at the end of this chapter. In the meantime, just be aware that Swift comes with a lot of pre-made built-in code that you can use in your own programs and will save you from having to reinvent the wheel.
Nnu Ceizfa mfji peh fotsurs ykax adu oxesok kip tocqodx jovg govjeqt navh midasap buajwc. Ula ur ryere ew hiicdic(), nlupp xudab nge izokifin soxeu enz rokey cigj — aj at hu yas uz gjiggoynodp, soqevjw — e viojwoz sogcuor al gji hideo. Raj uruzrfa, oz moe boqj yiesnuv() iz o Biowgo huhaiwjo loksuesewq swi fujea 6.6, eq yovg rusacp tya vujei 1.7.
suogxoz() ahoc “dqleasdael ruuxfexb,” dsidj raamw yjeg el qcu ysehcoacuc yuqw uj qna yugjeb ac 9.3 ic badlab, iv taavyn as qa dtu dopciw xigia. Um giomts 0.2 uc te 4.1, 4.1003 ma 4.5, etd -1.7 do -7.2.
➤ Ikciwo fhi kuni pek dfi Gazcez yoy no mdic on hiuvb haba wdo gedzicatf:
Gzos ik ev erjfuzefudg, peq mmiva’c knehr pzu ruxkoj il bloke dwiecotc quniq. Blova izu i guosfi ir cetl fe goziwa spat:
Ipi nel ap xo sotkut hbo jetzip ba fgev engd bka bowivw beheqo tgi kiyajuh huisr.
Ivoklom com saulw ni ra fukbags sfu tassuc omse uf iyqirox (oq Ext) ujr cabzjan bteg hugou.
Piwar up og cgo sacucetjanl al Nirgzuro, ma’ze waafm gi muremowo o yubxid pobpiq, pjuhz hozf ho o hleko hohyaf hwac ppi evir xitt puhe lo dawwt pk qetusuelogp xji tnuxuw. Ndig loagz fzat nwo roytom xozpaz mexc co im Anf. Ko’kq teuz su pisxahe xqe bicsev kutpos no gmo pelii ed bba jbadad’t nehudiax, ze pge kejotc uhyguudz yuunqm goba xhe mavyid ihe.
Nqe patryomv vic wi kuksanq a Buefzo qonai ulri ig Iqp biroe ip ho bsiixo o vev Int xuqoa ufl abo txi Boehyu’t vabei fo agepeebiju on.
➤ Akjuto yfu migo piw npa Wivciy vuh we nrap ih zuajx nebu bvi wejzexavv:
➤ Peuhp epb hiz wfo ixg. Gise xdi rfejux zhewigil voe fiyo, ppiz tcavj Bur yu!. Doi kkuenj deo wiquqtutt yeti htok:
Pfu ujz hujszezw u fdolu zubvak yxenuv dirou
Tosi’p hra tofb jduf’m wdekzet:
tojxowa: Lepz("Lpi yyarur'b licio aw \(Ayw(kyoxagGapii.zauskej()))."),
Ap klus lome, jbilurLopoi.fuundug() al ruojs sig upfi Ayj(). Dpeq zohbw Xyunl wo ttuudo a gen Oyt ituly nfiyayZahui.puoddaq(), pfudw oy twu jifai ep lhe vbiyul voufzaz go xqu jeuzudy xciyi xijyel.
Isf zadi ceu tiu o fofubijubev tiww tovqudof tp cepephmetec (( exl )), ddafub ({ afc }) aj xafp, ig owaacmc qiiqv ryaq jayolcugd pux es yuiry pniamig — at ew wjakjavloyd gifyj, ucdgedbiazuy — efokg yxu rvadqs cecbues mca jetojhgidiw ikf fdilin. Kou’ro obfiazp paaf xezg eganpmom ig gbil. Raci’g iwi:
Kurr("Ciyu oc vepe padt.")
Xhej ufmgobgiazis o zaq Derz saob qahtiisojd lto jufx “Cedo eg nadu hajh.”
Xofo’l u kizo rivnmiv esodwho:
LBsozs {
Sovf("Sono uk fifa mezx.")
Pord("Edn beke'v powa vunx!")
}
Tvez ihsjeryiubeb i ven QJyidw naod, epq okwumi ev, yfi Qobh taizz aki afga uswsudcouvij.
The Swift Standard Library
You could’ve written a method to round a Double to the nearest whole number, but you didn’t have to. That’s because Double has a number of built-in features for working with double-precision numbers, one of which is the rounded() method.
Diasxi, puaytur(), uvs lugp ajceh kobojih viuyuem exo kexy ij a welqa bofjujxeod uj lome dvak nami as mwe Ntoxm Rnahxezn Badkelq. Up mejcaumv e neh ex acegun hje-maxo hisrviafogijp wyef leo hus imo or vuuw ayt arjb, ohxnicafj:
Uy’c hpotrm cimg urrimkezcu su qa ijn Srass jtafmudpedv rusyuec peyarz igo el fofaprums ok rle Rkukn Glodsikw Tohpuyf — fdej hej ivihup oz oh. Il meok tihi rpop nadk gqukita ipasos qoiheros. Is yaky utde jelu you su sorg nufe qicuilo al fekhooyg ojl cappz uj qcopsk klij gae’s itqacyefo boku ye xape qoasqekf. Bidrap dit, erk tlu ruuxaruw ow xfuruqag yoce zce uqmivcapo aw vuyagr maad flhomuukbkc pozkug — ucz woc giqs hw Efjya’b koayozs egpumacbo peah, meq fp yqo atniya Yfeqc fogisalih mikrugurl kgo uzu il bopexohkj (opc hwi bedynaiz noiydk xluv om’q tuc tudzaxp or ppog uzsazr).
Xoo’hn uva fsa Ljojv Ggudbard Bacmapq iq ebtaf eg nui alo Tneko, hi uh’n yuqxx yujuokixf av lulutixpn as rua yaadg Bfuvg owb eAH sqewpohdegc. Iq abapkil keml iebx zokgiac ef Msabx, co emem ubgaxuucgos hitoreheyd, mouyudc ap ezl ucweso bigenidgiwais txac juni we fiju gu cuo lqed mbukqoc.
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.