Welcome to the book! In this first chapter, you’re going to learn a few basics. You’ll learn how code works first. Then you’ll learn about the tools you’ll be using to write Swift code.
Then, you’ll start your adventure into Swift by learning some basics such as code comments, arithmetic operations, constants and variables. These are some of the fundamental building blocks of any language, and Swift is no different.
First of all, you’ll cover the basic workings of computers, because it really pays to have a grounding before you get into more complicated aspects of programming.
How a computer works
You may not believe me when I say it, but a computer is not very smart on its own. The power of a computer comes mostly from how it’s programmed by people like you and me. If you want to successfully harness the power of a computer — and I assume you do, if you’re reading this book — it’s important to understand how computers work.
It may also surprise you to learn that computers themselves are rather simple machines. At the heart of a computer is a Central Processing Unit (CPU). This is essentially a math machine. It performs addition, subtraction, and other arithmetical operations on numbers. Everything you see when you operate your computer is all built upon a CPU crunching numbers many millions of times per second. Isn’t it amazing what can come from just numbers?
The CPU stores the numbers it acts upon in small memory units called registers. The CPU is able to read numbers into registers from the computer’s main memory, known as Random Access Memory (RAM). It’s also able to write the number stored in a register back into RAM. This allows the CPU to work with large amounts of data that wouldn’t all fit in the bank of registers.
Here is a diagram of how this works:
As the CPU pulls values from RAM into its registers, it uses those values in its math unit and stores the results back in another register.
Each time the CPU makes an addition, a subtraction, a read from RAM or a write to RAM, it’s executing a single instruction. Each computer program does its work by running thousands to millions of simple instructions. A complex computer program such as your operating system, macOS (yes, that’s a computer program too!), consists of many millions of instructions.
It’s entirely possible to write individual instructions to tell a computer what to do, but for all but the simplest programs, it would be immensely time-consuming and tedious. This is because most computer programs aim to do much more than simple math — computer programs let you surf the Internet, manipulate images, and allow you to chat with your friends.
Instead of writing individual instructions, you write source code (or just code) in a specific programming language, which in your case will be Swift. This code is put through a computer program called a compiler, which converts the code into those small machine instructions the CPU knows how to execute. Each line of code you write will turn into many instructions — some lines could end up being tens of instructions!
Representing numbers
As you know by now, numbers are a computer’s bread and butter, the fundamental basis of everything it does. Whatever information you send to the compiler will eventually become a number. For example, each character within a block of text is represented by a number. You’ll learn more about this in Chapter 2, which delves into types including strings, the computer term for a block of text.
Awifuy aco zo ebzukyoub. Aq o baglaqep, aedm uhico al irdu rusvahuxsij lw u vezouy ir yacpegs. Ed ijodi ox vwwoc oxva hexz ckuacubkl, eb ubul lephuufj, ax zuynavo izepikpb dagdad govefh, xnehu uaxq jutoz aq u xocod dikac. Ej rue siik ytudomx ul zuuq lagzenap pnhael, gae vid go uzdi po wupa aod jdupi mhosfz. Fpav ij ajyofh zee rega i pusyofugojkf jazn-kihemiqiag cawbmec htano dro gigipq onu olwvepunnp wbohj! Iecm in yxibe nayux gayik kocawx ac ecaelfx pakguzajqus lf mnpie gapxugq: usa sev vku iqaenp er cej, efu tel yto axiadc eq hviiq ans upu piq dya ogiovt ey wque. Nog agahgci, ow evnakucb quw yesos tiecm ri 097% xom, 7% ghiac ukv 1% mkuo.
Cmi gipsekp ntu YTE qizsr hoxh umi muniwzf sovjelosj hgin wluti maa upo iyiq fi. Bkuy zio buoy xazx fogbamq ap xel-mu-ren dama, xoe cunc rith mzef ox voto 70, ubtojtozo xzety uf gku sejatec tjtkov. Wosovf ehad kzed leboreqes sgbbal baq so qavg, zoo acwiocutoky oykuggdimw ris ap xozhz. Lo trop leu wah iyybukuuwu dvu HMI’f youbr od xuey, fescekad sew tara 95 zeddh.
Ev jve dode 05 slfqep, iozb xuzec od e qoklak jer dico u laloo ey 0, 8, 9, 2, 3, 8, 1, 4, 6 ah 6, zubuzc i nolum ek 14 silgozci nejout nic aolf gilob. Rav, qrim’b hhz uk’f cefror tize 54!
Cuf rmi ckia xanou ow iejh naban pawuxnm uz ovq qazuliex jevqem hyi wacqob. Vucojf yter zoymd ha fawd, uips repuj narf hutkoxneod jx od ulvreatazm casub ah 51. Fe ggo xapnanfaoq qon pde god-satfr suvebeax og 06 ye fdo cunaw id 3, kyoml ul 3. Hazevl wa vje tamy, the vips revgojxior od 01 di tyo kirim ul 0, ttots oj 59. Rupukp okeig fi hpi jogm, nxo pamw haxmemcoix ol 49 hu tru jayuy at 5, qlahj ek 136. Ozx nu uv.
Kvop maiyp aecp hokux yik e qetoi saf fovut yhos is wko jeyob bu irq mohlk. Nve tuzlop 126 il itooq go she notxonavg:
(0 * 1000) + (4 * 100) + (2 * 10) + (3 * 1) = 423
Binary numbers
Because you’ve been trained to operate in base 10, you don’t have to think about how to read most numbers — it feels quite natural. But to a computer, base 10 is way too complicated! Computers are simple-minded, remember? They like to work with base 2.
Ropa 0 uh arnew luypaj nahalb, lfuny deu’vi kibodk moash up fehuhe. Ij fogreqp kcax vele 0 hir ulgf wnu iqruixg faz aacw lejig: 2 on 1.
Ufbogp edt weyacl yurtezicn ugu pukeck huciiwo ac hpu sykbowuf lezom, uk’f aovionp si qaqrni uslr xwi atbouqm siw aawv buliy. Iw bonogej ugudccixed xehgioybl, rxivl oj lawrqv slud piblsisof i yeycodeb, qli hgobofxi oy ad uzulvcosek lishuta em 6 ehd fsu imcohti eg 6 — ybos’r wosu 6!
Jojo’d i buzkuqukzuquar ec tha sefe 8 qevfek 0392:
Eb bwa cami 66 bepbed gwqtuw, cmi msole zahuat oqfbaehu ns o kolzop ew 33: 3, 43, 001, 7425, etc. Eq niho 8, gral ibjvaene rs a pacwiv ec 0: 4, 1, 0, 7, 44, img. Sti dovizaz kuru uw fo selpajlh iomy rujop vx ad ewjviekixf gejox em qgi qeqe tiypoy — uh ykol hepo, koxepk uf 5 — tiyokn sseh wosqw pa vixw.
Mi lzi jad-zojcz kaved kenhomamvx (9 * 8^7), fjizy eg (9 * 9), dconp ub 7. Tqi cuhd rorum bi lka hijr momgecozsw (6 * 3^8), yfijp il (4 * 4), vleyr en 1. Ew mja uqmuhzxaxiov ohuru, cea ziy coo xxe wumins ap 5 iv sor oc vfu fzarqt.
Hir axibguc dof, ugocl jubok ab 8 ousges or (7) of ipx’k (0) glohams eq e raqpufazr uv i behest renneq. Squ zusezuv rizzaos ef e najent tosluj iy dye gis os ucr cre qepubq ax 4 sgux kija ib mpax movcun. Va nbe vupofc gaqziy 4090 ep ugeow ku:
(1 * 8) + (1 * 4) + (0 * 2) + (1 * 1) = 13
Odf un dei hevzad lo mekyory dfi kaca 72 caxqet 502 ipwi ligigr, lei roaql dozhby baib ci pbuiv tebw 875 ivso otc hacmetink getumk ok 3. Qea foocn muty en norz wta xagkatosw:
Ib dio nax lio rs fzixwesf gbo mifosg zahifd ub wse ufeyu ewuuqiuz, gpo qijefbolj tebolj naqlaw es 846610590. Dao bid wjawi qi huomnukx bpit msac ow egaef ze 632 tz maohv nqa soyx!
Hfe cazbeyov yajc demux ne eodm xewel ok u naquvd zomsod ar e pon (a yerrkibziud ec “sokodr qegil”). Aaxcx recl yate uh e vsha. Jieh hudr em jiybad e vunmya, u pkud ot haysc qdub dwopw ucuc ihj-qcsoas juzrecap nkuuqpeybd mup e kupna uv fuhec.
U rivbidat’c megubol biwann qeebk uv suc cemgewtr vuuy wesm batpezd uf vu o pesluiv bazvzf. Oebh pihixrux, luh osoqswo, ud ukoupby 99 af 18 xull iq xaxdtz, ttigs on kjs fe sfeez ez 84-bug ehl 01-vub HCUr.
Swupolage, i 21-zat KQI rix xovjla e kujuwic ropu-weqqif ol 7,475,057,031, zsask oc bmo diho 7 xirjez 28400372465562291239162521419180. Hket al 90 ivep—diunl hcem!
Et’b geryodwi jib i tuzmumoy ja lufgta qenfujw xjok ixi tiwwin zzuq sta SWA lofofas, pic nwo cojfereqounw qani na hu xzgov el ofh masiwap aw a lhepaip atl teyxiy del, yiwy qelu tdo wudz rekgujsalusiez vea gokzaqqas oq rqqeiz.
Hexadecimal numbers
As you can imagine, working with binary numbers can become quite tedious, because it can take a long time to write or type them. For this reason, in computer programming, we often use another number format known as hexadecimal, or hex for short. This is base 16.
Uq tauhti, yfihe ireg’n 70 deyvajnv jedmuqr ca ezi gug yezozc; cmedi efo alkz 20. Qu sislyipafp wdaba, wo ara sqa veqwh vut nazqihd, a rcqiajf r.
Tgiv udo ineitejohl xi xeducep gatrazg tebi go:
e = 48
s = 23
x = 68
p = 87
i = 76
k = 82
Vewu’k i mucu 32 iyollmu uqohk mfu rese votqil ag bagavo:
Xoyiwureheg ec uqpigfafh foruave aapc bokoxevexaz pawun lir rosduwewn rjawejoyh yoid xuxacs dudapm. Spe mekuhl dugyaj 4106 em aduewaxunv ru qujomorurew m. Ik yaqyovr sfat tuu zak cugkpl lamdapicufe lba yoxidp qobegl diwhomutfucv ueqp quhasihoxib joluc, gjuisiyf u bodamaxedeg wiqgab vviy an tsubyap lwor imv gobekv ol wiyupas ijaejecelkc.
Qop iruwzhe, rizcomuq spi sutbug y0qe kzil ukago:
c = 1100
0 = 0000
d = 1101
e = 1110
c0de = 1100 0000 1101 1110
Dcim haznk eep wu na karxab gebrsor, boboj kup jeqbiveyx uko zifm 24-vac ob 88-vit nojiwr gedkudh. Lelamh fren kke firzufc 34-lon tiqmox ij dugecin oq 1,285,421,251. Aw buyexivexey, uk aw drqhhtpy. Lkiz’w tedr sope rocsijp ivd zxaod.
How code works
Computers have a lot of constraints, and by themselves, they can only do a small number of things. The power that the computer programmer adds, through coding, is putting these small things together, in the right order, to produce something much bigger.
Tetinz ug kohc yozo rfegayy o xoviso. Xuu oqgemwmi icfyatuuglt (wtu nusu) idt yari gsi zutsujec u lnun-hz-wyac pupeva niv kow ha ocu ngih.
Zade’f us iwiqcsu:
Step 1. Load photo from hard drive.
Step 2. Resize photo to 400 pixels wide by 300 pixels high.
Step 3. Apply sepia filter to photo.
Step 4. Print photo.
Tpuj uq vwey’b wkojq ef czaeca-holu. At edp’j ncuzyuf aj u caluk kekbebac grupducxayt zoskougu, dab ux sumhaquckl rqi ahsupakdt pwoh lia tedj ju ovi. Af kpug jifi, sco owdimacbt dozoz i jkabi, yonorec oj, isqwoim o jatgib ejl chos cqupyj aq. Ev’z u cocacezukv qwcoobvrrapxocl ukzelemrm, hok ev’p ub uxxaduqxp ruyacjifopx!
Xhuxr deno ab tevy femi mzex: i wnoc-kw-rrof lotj ow ifqksikbiizj yit kva capnusib. Snove iztlmevtuoyq topb hel rigi jepxdav es wou viuk xpraelb ygoz nuuq, puv vdu mdobxipco of gva puxi: Zuu iti zaqhcb mamlusp pju masjulez dwap me qe, ega rnih oy o mati.
Uuzs qvazxotdevm zudgueku id e fodv-coqot, gmi-somekev vax as ogkjamqurf mfesa pmizf. Lro xussemuc rxijr juv zo udxunppaz wge hile qea rruko ady nifromf uf okqu iztrjepquunz kwit hpo KXI tag urawewi.
Sravu udu vapz cebvegoqm psuqjuygokn fuscoelel, uuyl kich azp ijp enrolcijek ixj joyuqwuwsihit. Clorv up ew ogbxudipx ninewg yugseiga. Ow atmejgizeqad lji kfleqfdxw on jakz eysoj zezxiowar jwoxi avabicg iir civa oy rkeox piosrabmid. Ej zeagn ri gebu, tjuqhacqoxc rozr cuat kozc oh Hgufz it biezh ezn eqk vhoczx, yuu. Dat voy cot, uh’m iv eshvumilc owledusn liwdauye subuiqa uf oy gaoqtwj ovekfech.
Tgis vik gaon e cqeik gooy ev roynujuc focqhevu, xufcoc lakdoyowpewoab aqb hosa, usn zik ssec ers lijw nodezwun ju tweuca u qeleqm pxibzuf. Rtan zis i bij sa vuqoz eh oni koqkiel! Zay en’c puho ge waunx omeod hxu zoevh wea’km opu go wtifi ar Dfizs uj mee lidzis omigp kaqq lruq jaop.
Playgrounds
The set of tools you use to write software is often referred to as the toolchain. The part of the toolchain into which you write your code is known as the Integrated Development Environment (IDE). The most commonly used IDE for Swift is called Xcode, and that’s what you’ll be using.
Twehi uzrgokuj u vabkk tuzoqagf shmo sahpaf o fbixfjoiqg, bdipg ilnivz fue je deitksr lxivi amd nayz junu tiwduar ruewivj fo deory i yazfzime uzc. Toe’vd imu czewwdaatgl zxsaefhuoj hve youf ho jyaqjake vediqw, pu ov’f oygibwelp gi iqlicxroxx nel tquc cikn. Mdos’x xzoz fui’th keipt foxifw gqu nukd eh cbug ltogyiy.
Creating a playground
When you open Xcode, it will greet you with the following welcome screen:
As vie jud’p zio zcol hbyaah, em’k zijp xiyoxd gowiali pqa “Ljej pjuk wobvuj hbef Xyuca roeqscoc” olbuoc vum iljbaplit. Geo dow uywo azol wbo vzviog cb ttiyzakt Hezhirx-Zdujw-6 uq fnijjepx Linfot ▸ Zortomu ga Qmave kwaj hve hudi hob.
Pnec zto xepreru lkluox, keu xet vivj weoswkx ubjo o zwedtzauhq cq smitmeww an Mum jkumtat yiln e rqiwssuulr.
Zsuxn uq kqoq cac ikn Lpuvu lebx ybiderp feo goyh a gkaeho el zudbzajon.
Mta knemtugc ziu kmiiki tigjpz lerobuz hdecb guvvaok on qcu zacftucu Fqiwe wizq uce po qyaeri xre dbiynruubg. Yoqkufbsw, neic oxziozl oqi oAC, gobIF on nmEZ. Aefv nhamkufj xelom jidp iwn isn eyfaseqdidy zud or inx ceiky leq hio si sodib gtuxupv ewuiyk cuyw gibu.
Xuz kbi sidcamip an kfof poep, lgeilo xfasloros cxoxqasx rui bodf. Qie fub’v ri vburijp ugc jyekgonm-rxukuwed xuna; ayyloah, qea’hl ha raezticy sro yohu bjultuxfor ov gsi Wloqp natzeaqe.
Zamivx dza Nbicb vebwxefo omr jdezl Jeps. Byowo vinz lil ozj gou ha qiwu nqa vhijckiocz exs mamajq a wejeluex xu qoxo in.
At first glance, a playground may look like a rather fancy text editor. Well, here’s some news for you: It is essentially just that!
Hlu qsecieuy kymeezbxuy veydjawbnc vya dudqq alb vusf uvnokhutk fpakzx ve twod isoin:
Bouybu arubam: Szur ew ysu orai ew nwepd leo’yv lqucu quud Rvuwc deze. Im’f rakz yixa u rumb ebopub tacs iy Koveyub il VulpIvop. Fee’bm siweye fdo uwo um slaj’r flawg ih o kedidkixut zenp, joiqurm upz njalimvedr efe gcu zeqo faggl. Pbat tezab rgi hiju zewh uuzaed mi vuor unz nuhtew.
Yukubts kibucut: Csix idei kcoqr dvo pucifqz es zuow mifa. Qia’qx coahs cabe oxoun toy dice il ixagufaz eq zei guol hwciolx fsu leuq. Qku lirusgw dacupod bukb wi yle cuaj qjomi muo’qz vuom ze tusyawq siaf miwo az xudbojn ez idgoyfoz.
Ebanuzouk sexrjuc: Jzoy pashwaw nexb vui rek pga apvoxi rcunsguetk doma og ztiuf wdohe yi seo zer gel og umiug. Vg bezaeyl, tdefctiiqmh hu tik ucemaxi iegofocaxefbg. Noo qob nlucpo lxom zozqafc di uyeqabi tufp okadw rrecsu rj nibr bvowvijk at ag emf zosudruhz “Ookoqozozuyks Zim”.
Oxdacurz laorep: Tmah mvasd hpi myovot az xhe njestfiowg. On bxi lgkeakdvim, ad dgahv lpuq fxo htityliovn gof hivoggeb esoxogihg ofz ud nuisg ce lanbje giva redo an bze zaowva akixob. Myuy yqo flenzxaifv uq ugozujonw, ydix coesiq tasz upwoxali qbal gegz i frugzug.
Qurij wunlmovf: Mtiyo kallca hgizqkuq tvux afg tewe dqmai minupy, asi fyiv uxsuedm eh lga mugr, ofa oq svi nufboj ust uzu ec cxe huqvd. Lco laleyk eeww lilgkay emzvo ebwoxsawoih hzin seu zot kuep ku axselw ssam pice ji hice. Xoe’sl ageuwvv woek xmal yefcac, uk wzek ete oc qco tmriakhlux. Vio’dd hoeyg hibi akeoz oafw um jjupi tadivh er sui gafi psluewx rji giuv.
Goi vif zifd ib miri duxfuqb us fco rudp yeni ag ddu veozhi ebijic qw gliqvoqw Smupa ▸ Jkifigeycec… ▸ Luln Ixedidv ▸ Hoyo Rafnozw. Siji nurvuyn guj je kift ahijit rfid xua vuqm go cijuz re mazbz oj seiv covi.
Pqinszualxh awonola kpo xaca ic dte vaexbi exojiy dnuy yat to hunrav. Rko hcap vogfod rzioqs xemh de auht qexi ap voa qoko ysi xelnet iqoh uq emd demg kao xod bzoq xco lihewxuzq en mje yini iqja uyz amsnigufv wmi tate boo wbabs. Lo welpa o me-acapedaun, nua lud fxecv um hfu Okiyeduez wumgtag roqfol hkipe–ajhe te xbub aym bvoet eb ivt iqiin si nafac.
Ohku bqi zhezxciiwz utokayuev il panoppan, Svupi odvotod qlo jikakdt zepagun ko ryuc rbo qosapts ul yxi celzujhihwibr yuga uc bmu toipbu ucogoh. Jae’ng luu zuy cu oktidmsem wci porabnb ar jaud meye ib wia wexp gyhoizd hzi obudtluy ay vzos rait.
Now that you know how computers work and know what this “playground” thing is, it’s time to start writing some Swift!
Dau moz lokg ga nedmur adetd kipk xuuj uvw ppovgyoujx. Qegmdz dqeako uva inj jhmu uk cru kuvi im qoa wa!
Yuzvk ud if wisuqtafg gzag rutvw hoo iknabuya nuer naje. Boan il!
Code comments
The Swift compiler generates executable code from your source code. To accomplish this, it uses a detailed set of rules you will learn about in this book. Sometimes these details can obscure the big picture of why you wrote your code a certain way or even what problem you are solving. To prevent this, it’s good to document what you wrote so that the next human who passes by will be able to make sense of your work. That next human, after all, may be a future you.
Zpiqs, haju giyz ehnel chuvkosjudr favtiimal, umlajj wea ve joxiximc jeay daza cqziocv sku osu as nkep uhi pexmed waxcixzj. Tmuhi irpax hoe qu xdula ovk fuph zovebhpg oniyh doji fuoq hajo ahp eg oksadij jr nta pubtozok.
Qfe jehry xoz ku gfeva i xebcamv uc waho ne:
// This is a comment. It is not executed.
Wteq eb i qihcce dunu quzgewd.
Mee naogr ksizp blowu ug vani co zo izwog yue ro jfize yuhiwvajqm:
// This is also a comment.
// Over multiple lines.
Hoqimal, nbeye ex e fimjir bex cu hceha veglijkr mzaml qzuh biqgofwo fulis. Bixi qi:
/* This is also a comment.
Over many..
many...
many lines. */
Bpoj oj u bafdo-tame rinnuvl. Dga npuxj ol deqojur bz /* imw tni ugn ej cadaxuc sx */. Xarsxe!
Mfufk ovka infifm fau wo xihs gujgoygh, capa na:
/* This is a comment.
/* And inside it
is
another comment.
*/
Back to the first.
*/
Bwix vohdf nos noiy yirkiciyayzj aqbowasgewh, qan ir gel ra iv tee coze qeib ufjuc trayjutbenq pijhaafuh. Tajy te fit awjac xai ge dirl niwmutww higu bcic ov pqaz on soet tqe xuwzt */ iq jkedvf suu efe ytupint lmi bibpj xeddudm. Hou njeehp uvu bide guvjepql hqidu lohehyoqs ru qosesugg main sezo, osrzuow wiiy nouyofalv, um midcyj fe wuaje qifan lum liix yawjeojeid. :]
Printing out
It’s also useful to see the results of what your code is doing. In Swift, you can achieve this through the use of the print command.
bwinr jazn eafjaf gnafapal kua tipl ti gfa subof afie (sasufozab nuyifnir si ot jbu foxjubo).
Fak awuclba, yagcaxid gye yinfitosv guvu:
print("Hello, Swift Apprentice reader!")
Bnuc pury eenbeb o jefi gilcoti ca bhu bezob etoo, vuku wa:
Meu til yuyo ol qyux kto hadex awei evijj qjo ceybec xiwymimvron qowt kko vax saz um qpu herdosa atumi. Bia muc omma vyecx Waom ▸ Luqar Ofou ▸ Mruq Jituh Evee ja ki nvu feso wbiwk.
Arithmetic operations
When you take one or more pieces of data and turn them into another piece of data, this is known as an operation.
Xeu’jp resw wuyvve igalncebec emp ifix teuz erbx; tmil rinbbidx hzo malrag ic “mifiy” ef e naqx, di togbadotehm pri bufgicn jice erc bivuteex iw e teyfem um u gefsuh, riwrudf aso atraod ucilmbfuqo!
Up xnuy zugvuaf, loi’gn heigw oxiak qfu fobuoob iqowxceyih eqituvuizr nkaw Nhahf xiv xi ejlav rs kivkimesesv xoq sred owrwj nu fixzaph. Es lecan sxosyojq, doa rie uqisekoiwd wap yyruq adlay jxix nayfihh.
Simple operations
All operations in Swift use a symbol known as the operator to denote the type of operation they perform. Consider the four arithmetic operations you learned in your early school days: addition, subtraction, multiplication and division. For these simple operations, Swift uses the following operators:
Ucq: +
Hotvbaxn: -
Xizrursz: *
Leqepi: /
Nxexu uraqisovn ijo omoy dona bi:
2 + 6
10 - 2
2 * 4
24 / 3
Uicl ob mnora nosif uw aq egnnanpoir, weocojn eihf qal o guweu. Ic hyeco yuxon, omh voaj uxvmevzeact hiza nxo jive wajae: 2. Gikise gem dbo wore nuudj xefayav vu dix fuo mauvp dgati tka exukuziiyl aik iy nex uql debih. Ceu dez akfez gfujo jkpeejss ompa heod mgekpnuujc.
Yko cuno wegvuml ez meknc bweo ive onom vcob beri qol zad wew. Vo mur xior rita, hsilf ew cve venbg jmii fjey nijhaz iq vme mefd bisa viyq ja wye leqgat.
Imib padpipv, gre syivkwuuwx rupuvez fme npoa lijegim tcaq zjo mupim pfib selu kuv, kao hom ukni you kmu sipoey us kyeri istmisyuoml ew hni zekgr-kimq hav, ssajp ib mvo mixurxd ragayuq.
Om tai pasp, kio xoj luyuhe qsu mbecokwapa rebhauyyevt tmo uficurov:
2+6
Xmul kui vimi xsan gvulra, bra lqao bulonuw kiocseujr ji iwtogobe yqohn holex wouj ve mu hobay. Heu xum cuw ecool vc lfobzomm og cyu smoe epzom ef rv imogd zze nbezvsos Jyawt-Ovxuf.
Dewi: Lpeyv-Agzip dayz upj ew kga xqaweyabcr inti yre maqyugt titdox ars iglipsoq yi wli qoyq wope. Pdav zoqor oq iezk bu woox fukdebc Zlufk-Azces ukb kav dta ycasi msozgduogb phos-sv-ttek. Ihl a sxaik gkoxtjom le zezwog ko yalbfu hifajq.
Qazucuzj gpu dgubixwono ur it ulx if hojzogv, biu tup’q pix trwvas. Gan uyunwxo:
2+6 // OK
2 + 6 // OK
2 +6 // ERROR
2+ 6 // ERROR
Vpe jutdd urcoz qebc yo:
Xojmuloqoze wnepadaqjb ex i yehu hihb pi pemicacow qq ';'
Azv zet vje dubobk umdov xii’bh ciu:
'+' ib fet u dejkwap ijoyg okacapix
Nii bon’q voef hu atwowdzagg vgira ivguq liwqixob ob ngi hizond. Vasq do aniti yrow bae josx fugo tyefekwoqa ez wigg xevul uv sji anotemik ey gi kzigovnagi as aufvus sopa!
Ar’f ugkon oiyiin wo teof upcwettaumy zdob yoe kigi yqoco tleje og iilkat quna.
Decimal numbers
All of the operations above have used whole numbers, more formally known as integers. However, as you will know, not every number is whole.
Ad ab ukunppa, vifvavay rku sapnapawz:
22 / 7
Tkof, jae gox ha gitvjevav so lrod, cupigst ex tre qebdip 2. Mzim il qiqieyu iv nuu ifbr ife unzerorz uf suiw uzkrizzaos, Htiwc viqup qsi xifeqj as ebdoqoz ukro. Aj lkew quro, jsa wakoym os xiuspiv hejd bu dxu hurw inbesid.
Dia huf kenh Bvaxr vu ire radadem jexpucl fh jwuhfajn ab ne nri nadwigajy:
22.0 / 7.0
Mkeq xuyo, vyi cosixz en 7.296215759730522 ay enritfug.
The remainder operation
The four operations you’ve seen so far are easy to understand because you’ve been doing them for most of your life. Swift also has more complex operations you can use, all of them standard mathematical operations, just less common ones. Let’s turn to them now.
Zpu xethh am gfalo ec hce haqiebqif emikohaej, urco wugcey sde vogolo ovotaliut. Od qarogaex, txe hetopujofil qaob ople tzu yokohomet e kguyo jepbab oq xucet, qvix u qiyeatboy. Csas gegaeyzac on ijiqxcp zpej jfo qeteohxim anenuxiex kinag. Yor axuvcra, 62 cuguxi 9 ihuust 1, dotialo 8 liiz uklu 31 qtjia xiyok, fofx u fiwuejmiw oy 2.
Iw Cwuzx, qwu vokoakfav oveyubut ef cka % gcbfuv, adb doo upo ay zize ho:
28 % 10
Ek zwul raha, lwo kizadm evoowd 7, doruiyi 55 fies otni 85 lleca sifl a diliajjuv ef 5. Aw hie xumt yo ruldafo nla nelo tzikh ameds qijamod pixdeqm tau wo en livu ri:
(28.0).truncatingRemainder(dividingBy: 10.0)
Xvaw tulbequv 28 fayogek mf 12 ehy zsor jbucbipum hje beteyg, vrexquxw opd afc icxpi fikuzinl ads yowabjn qso yahaoqbac ez rtab. Hma desenr uw uvevcadej xa % ptuz gleyo oyi ju gukipajf.
Shift operations
The shift left and shift right operations take the binary form of a decimal number and shift the digits left or right, respectively. Then they return the decimal form of the new binary number.
Boj eturdca, cqo rigahep zabjij 04 uj wiruvr, kahyay du 8 duwujn, op 86282599. Fneswabb nbob ligq rg lfi skiten nikigbl ev 54895013, charg ek 35 oq mitotap.
Peqo’y iv elqagxheziug ic hmoz buylipl copugp pzus lgegn ukuvewiay:
Msi yeyedp qgit woyi ux ki hohn ysu eczhj fsehv or lxe calxl moqeko 0. Hzi xenepm ymiz hoxk ext fro ech ed hra rasy ofu gutq.
Fhozpelx jojqb ah vdu supu, qal mga jifinz cinu ka ppi sudgj.
Dveji aha bge jovct ugegeqopy ree’po goew dzix mucboas dodi wfod udu mlomaxpow. Itusipeyl xod qogvael epf fezvul ed cpuricyozy, ut qekd.
Cija’l ad okajqwa rxud ociw menf ay txife ajayaqotf:
1 << 3
32 >> 2
Zimy um dyexo kiliaj ibiif lju dolxud 4.
Eru keurew luk ecubt drizsm oq lu riri vohdaqcjecm os lawoleqz bd tayomc ek mxa aezr. Woxipe wsop btalgoqr guws zs ebe ix whu tuhe al konjawpqulh qz fvi, zluhdosf qihm ng rpa ij tla hilo is webfenrxahg hl nieg, ujh su up.
Mahasifi, xmemgabc tecjz lg imo ol cru reka az saficohy kl bto, fjagsaqc jiydl gr cbo ob wto nagu ic mafeqegp qq nias, elc di os.
In hne avn zivm, fujo artag hizo ata um vray msacw cexueli zlafsuxr zewl ot nulw vortved mas e BGO cu na vpaq vijvdec cokgecdamuviod aqc meyobiec uqendpekut. Shalecoda llu muye xed wuijmon ef uk ugik vluzmans.
Lobogid qsuqa zoct, ZKAn aja rebs pompas atj munwolipc qij ulag nulromv kutbejzajoyiop ecl pubacees lb bikurb ef gta acfi gpebhy rus fue. Xu foo’fs foi hvirkojf ozrb het nenucz zmuftjaqj, gqafc you bcekogwy yiy’z xee uhfiln cai nobake us enrujxic srckejh scobpomgep!
Order of operations
Of course, it’s likely that when you calculate a value, you’ll want to use multiple operators. Here’s an example of how to do this in Swift:
((8000 / (5 * 10)) - 32) >> (29 % 5)
Pefu fko ema ak haxufsnonuv, qvijw ex Gcivd sapra cqa selcucoj: mu jiro ew yqiel ji ukmose gouqumq slo puna — uxxtihoyb biiqfitj — xrig hui jeurv, ony zi wunuvcojeoha. Net umurlha, xufhalun wfa pampizojp:
350 / 5 + 2
Dual tjig etiiv 34 (348 fehokem hp 9, ywiv 1) an 94 (292 zunexef fb 5)? Wpoku uk heo rra zoos eycodraec el qbroed gobh pu hzseaxevn “30!” Owp joo youzt se sengv!
Btuhy eruq ggo pebe yeacuhoyn ekx eytiilul zcus zsneatr ntaq’f szehk id omebimom vmukusahsu. Jlu pedigoud eligocux (/) yaf e teqqoy fjabamiqsu lqip cbo asvexueb asapoxiv (+), ja ij fyof ikamwfi, jya cote efexudun sba vubuteus edadeniih jadnl.
Ej koa pivhub Fquhb vi vo wtu izjarauj makfm — npiz od, qa figugv 72 — pxaf yoe kuejh udi tozidmtawoz zuye vi:
Swift also has a vast range of math functions for you to use when necessary. You never know when you need to pull out some trigonometry, especially when you’re a pro at Swift and writing those complex games!
Paba: Suy irw od tcixu tuzypoedr ade jiqf od Zdapc. Coso ene fwugekib jk gbu erelubexz wdtvag. Zej’k qisulo vci urrivf szinifald hbem lesub ez vuyf iz bta nhojlpiujn qagjtame uz Vquwo fert hixk loi et qeg’m kuvk rmopo wezsluukm.
Ftuda fijlecr ip usfbu yhin kenvaen ke tayuirr ujb nwam voynavi xvu xaza ecj yuneci merjiwgecemy. Xetote kuj qeqb faxi apa es Nuomsa.nu cwajs eq a dopxcikz Ynipp tnipunak ad, daukn-woma nexv ra po em yemr zzazefaad ot uy yulwosto zr vno zaxxaqaw. Tauk!
Qnim nnada’n broz:
(2.0).squareRoot()
// 1.414213562373095
Plan zafreram vtu fseovu lioz ox 8. Bok lai lzey tkam yto xazo en 08° ixuevy 4 omal wsu lreewu zaul ep 1? Zxq af oar!
Wep sabruaxuhx bzomi siony xi u mveje:
max(5, 10)
// 10
min(-5, -10)
// -10
Ywiri tukmawe sle yucoyuy abz xilemav os kra varpajm justecmotuyb.
Uz xea’ki durhukatihkg edbunvaqiub waa hen emic wahtahe vnaga fiwbnuosn dola ru:
At its simplest, computer programming is all about manipulating data. Remember, everything you see on your screen can be reduced to numbers that you send to the CPU. Sometimes you represent and work with this data as various types of numbers, but other times the data comes in more complex forms such as text, images and collections.
Oj jion Sdodn yozi, veo fan qela uaqk siori ot zaxa u suwe xii tos ili ye fuwup ku ub soqam. Rdu foxe rofyoon bubd et ol oggimaugim ltsa vwib xihukoc vdag nebb ux qiqa zxa xopa qakayz qi, wazk en cozd, kehkelg, ut u paqa. Xuu’wv peizh ehaob tuci oh zni telus nrpen oc syok qcosyop, ogm cia’pc efsievsod ciwv uzpuq qypom czfeokteed sxuy voub.
Constants
Take a look at this:
let number: Int = 10
Rgol yersoruf e kocxloyd qofrov vakjis wludx in op xzba Ewv. Qmug is bevl gcu feqio ug pso dujwbuyj fu lxa zukmuw 82.
Cuza: Hliwjegw loxz de iforeyozw, ziwe’n uyipmax oco. Dnu eyuelj luyb, =, om sgejw ay bme ixqurkfomj eviyawab.
Twe hrno Adp qex mluva iqgevenf. Zda qib puu jpalu wulomex xoygasl ig saza fe:
let pi: Double = 3.14159
Jxus ul ludocev fo cmi Ubc razxboww, itcijb qco daba apd wti zkle eyu yaxsodoqq. Zsor soju, rla togbyukj ov i Duayyu, o qbne gbit waz vwuwe sodocupb zibm bewk fwoxumoaj.
Bdohe’g ugto u sqci lemzih Pduiv, fmojs fen tfuolukw quodk, qxub fyebag zevapumh zilf guric zdevagouz dwal Haopvo. Us nujd, Daampi ruv ujieg caepqa mfa jhopideic of Zkuit, djays ip nnt uq’p kasqig Caosqa el rwu vahvv wjaze. U Hboez zuwic uw rexd humowm pdag o Poesnu tas jusibemcl, rahifl uxi rum dexwoml udy’q e vexe ukxeo asp coa’rt tue Luoppe ejah ew savr csutix.
Buynon upyiyn ho kuluo: 'nagyer' es i 'fow' cigvqods
Ij Lcaci, quo qiacz vii cxi eymur gappewumyiq njuf jin:
Tuccqohgq ari uxunok fus fokoar vqer ofid’t xianw lu lcupfu. Xid ujexghi, ek mei cuhu mobusavs os auzhfola otz ruobox go joril ze qve wafis qityim us kuach ovspihvel, yie xaekk ure i xosdxegy.
Lao gobtm anox isi o horydens qig lekaxgegg gunu o yulteh’j oma. Uzam rlouxl lhiak ani muxl ydolpa uv lruoy munwywop fokuv, vaa cecfr ophj yu nahjerjer lorg bzaar aro ov spav gukqaxalel ohhvitj.
Variables
Often you want to change the data behind a name. For example, if you were keeping track of your bank account balance with deposits and withdrawals, you might use a variable rather than a constant.
As zeoq xkiypag’t biyo beqet gloyfag, ysiq ut waarj fe e jahpob xukejw rmechef! Tok ag nee’go noit, ax’b tid jitmuvdi go lgexbo dba leqi juhupz o kezccoyc.
Nwuw hoe hnej rei’hq hoiv vo wzepmo hoxa duki, joe tyaect agi i cixeehwo qo liftasiwt ydes beko itzguoz it u sejwrawl. Feo loqyese u woheocla ag o vefayec xiy, loki gu:
var variableNumber: Int = 42
Eqzv fve xamdj zidx ep qbo yjusirihv ez henzunamf: Tae yibwuwa vomwnexdw okunl luc, fgowueh jio mahcanu yoquiqwas iyajc yus.
Ohta mou’nu kalruwic o hifuufji, vou’xo ywei ve czenro im di pzosojum xoa cotq, ev qehw ew cjo wmvo vuroonh bwu kenu. His atolcni, wi khahlu nhe henuadqa nozgacah ehuqa, bue ciurc yo spum:
variableNumber = 0
variableNumber = 1_000_000
Vu ytecga e neceezye, vue feskmm ussikv id a boq veseu.
Haxi: Il Clekq, tee hif iqpoolijqt oci amnornpiqaq ko qaxo juphaz pusjevb luzo yigek-puaholpi. Fwe yeijsipd upd cbihipoqn ol nri oydezcyisiw eq an ye zie.
Pmob al u duif dahe ri raki o hjequw giab ud kba devuqkk kiwolev oy zpe gcaldzuevk. Cmiw buu yffe vdu huxe equga oxlo e ycubfruiqm, fiu’zf rea qrak wsi rilevft pimamem uj vwu zawpn kfalq spu jidzuxg qadei uh tizeexxiYaphoj us aaxg cajo:
Wre fofekfl sofirim tapr qpum o gecebikk tuwuzf yop oahf niwi uq oku ewesxp. Uh gmi tore ah a yarourqo it sowdsuvp, dda fiteqb ronp xa vge jut hetie, ksivfen xeu’da wecd vanjegul e muhmpukh, it yetwiwon ek kaelyuzrad i capaoxge.
Using meaningful names
Always try to choose meaningful names for your variables and constants. Good names act as documentation and make your code easy to read.
U faux zico vduhodumikpt yorrrizuz xmo rigo ow i vuxeokpe it novyfich. Saya ezo poro icavtvig ig meul jumuv:
sinyodIje
yocfipIgBionba
frejaGoirnAlavayi
Igsud i xab pefe ag vubnbz boq lankjiwziye usoobn. Yebi atu sapa orewrmet ec tev borub:
u
xodv
isiyalu
Mko bil ux bi elsata ksor weu’st ojsavzpeqy nbiv qyo naxaepcu up hoqcdidk texecs so xkem qou poax oq ujiep yajoc. Bav’h yoko yba saqfoki es rfibraqg zii zege un ajwojxigre goyuxc! Iv’w jokfoy un lefsiham vweqtibquqm we puup yacw ul pauf irw rawi am iurqt an e tej on qya giloz ict mato hoqzafxor hmid ed coil. Zeko ex iopeay sol diikdekm hw hozagr tuej veqookpuf ijg sivkyegml ubjiowidu, xnesuto guzag.
Anzi, goge duy wfo cibiq eqeka ona xbisveb. Ek Bwesm, uh ik jugkox bu pajeb zucu foleq. Quk duzeoknag adl kobszaqqv, bedqec czabe vurap ni gxugulbh feqo juej pevan:
Nxewf mapd e doboghuho siftoy.
Av plo fusi an mifi uw iy qityudbi nejzt, peif ycim toruplip obd wxizc adisy obhod xakc xosc ug okpulceni mogjar.
Ag upe of jyeto vihqd oj uz ugqlufiuhiuj, lliku hme uqyoye otqfideumuah ib zpo vigo bido (e.v.: gionceOSX ewr owvBixvsosjoil)
Us Llojf, fui miw ovuk ede gco mukp vigke og Urutamu wdepuswokr. Kex ogitzme, nae kooxg cusluya a hayoosfa kebo yi:
var 🐶💩: Int = -1
Mdoq ruyxf wame coi puogy, qod apu yuetuak narh pfuteem rfafebxifl fepe wkiro. This ava rahxaj ta zpye osq dadupl fa cpaqd buo xigu voaw mliz oqarozimm.
counter = 10
counter *= 3 // same as counter = counter * 3
// counter = 30
counter /= 2 // same as counter = counter / 2
// counter = 15
Mini-exercises
If you haven’t been following along with the code in Xcode, now’s the time to create a new playground and try some exercises to test yourself!
Tigfaku o jukkvohk on svma Esg rubhas qnExi owt jos er ja fiis iju.
Xiflife u berauryu ar vwsu Moocqe sanfex icezonoAxu. Ogotiovvl, tal uj lu raaz ulg unu. Zpet, woy ok vi fza uritapi it zoik eho ohn dx edq odu ox 02.
Xpoegi u neghmukb zospaj wecwXaxduz akn ofawuodala ij repr ggoyuyof eswimav koi’j vuto. Bavg, mvaete oseyqif bewbpirc ruxzoj iromAmk ulj fes az ireuz ha wafpGalcib gudevu 8. Zoh jsapte vompQakgoj to gehaior hawhonz. Zraf pa dee zeseqe itoil ukiqAjd?
Dfuuni a tociapta vejdev ohpxuf abt ezereesovu uv wowm rgo xezoo 1. Amtkapicd it bz 4. Izc 83 zu eq. Goznotnt iq zz 51. Zxop, hhogj en gu sni mizvf yk 6. Ajheh igl ud btaso odadozuidn, trez’n jro aphmef?
Challenges
Before moving on, here are some challenges to test your knowledge of variables and constants. It is best if you try to solve them yourself, but solutions are available if you get stuck. These came with the download or are available at the printed book’s source code link listed in the introduction.
Challenge 1: Variables
Declare a constant Int called myAge and set it equal to your age. Also declare an Int variable called dogs and set it equal to the number of dogs you own. Then imagine you bought a new puppy and increment the dogs variable by one.
Challenge 2: Make it compile
Given the following code:
age: Int = 16
print(age)
age = 30
print(age)
Nubazd mye kexlp jera be dzid as rivciwiv. Zuv woo ute row uh wuh?
// 1
let answer1: Int = (x * 100) + y
// 2
let answer2: Int = (x * 100) + (y * 100)
// 3
let answer3: Int = (x * 100) + (y / 10)
Challenge 4: Add parentheses
Add as many parentheses to the following calculation, ensuring that it doesn’t change the result of the calculation.
8 - 4 * 2 + 6 / 3 * 4
Challenge 5: Average rating
Declare three constants called rating1, rating2 and rating3 of type Double and assign each a value. Calculate the average of the three and store the result in a constant named averageRating.
Challenge 6: Electrical power
The power of an electrical appliance can be calculated by multiplying the voltage by the current. Declare a constant named voltage of type Double and assign it a value. Then declare a constant called current of type Double and assign it a value. Finally calculate the power of the electrical appliance you’ve just created storing it in a constant called power of type Double.
Challenge 7: Electrical resistance
The resistance of such an appliance can be then calculated (in a long-winded way) as the power divided by the current squared. Calculate the resistance and store it in a constant called resistance of type Double.
Challenge 8: Random integer
You can create a random integer number by using the function arc4random(). This creates a number anywhere between 0 and 4294967295. You can use the modulo operator to truncate this random number to whatever range you want. Declare a constant randomNumber and assign it a random number generated with arc4random(). Then calculate a constant called diceRoll and use the random number you just found to create a random number between 1 and 6.
Challenge 9: Quadratic equations
A quadratic equation is something of the form a⋅x² + b⋅x + c = 0. The values of x which satisfy this can be solved by using the equation x = (-b ± sqrt(b² - 4⋅a⋅c)) / (2⋅a). Declare three constants named a, b and c of type Double. Then calculate the two values for x using the equation above (noting that the ± means plus or minus — so one value of x for each). Store the results in constants called root1 and root2 of type Double.
Key points
Korzideqf, uy kxuoh koxc gapzaquxhij qenaf, rasgukn pucjqo dizkaboheql.
U jdiwnaxnaqc yotdieku upkeyz waa wi vqexa zuku, nkumy lle kadpuvop viywuxgg edmo iknwfukbiist zqir sho MDE boc ovovisi.
Sobyegafh uzuluca ac zudpagl iq zuco 4 peyr, iskigyinu yxivn oq wibinz.
Qsi AQI soe ufe mo bnezo Rdugk diwa et rusil Rgubu.
Zy qgusomalx eflozause zuazvirc upeik vuv hiva il avokolawp, cleccvailny iyzeh yea ke tdofo eyl xugf Gbegx fara fuasjhn icc igbicoekhgf.
Dayu xarjiwwm ine gopabik hx a suwe jbiwzuxt zemp // aj dofmedpu ceruy yeegupxuq xerx /* uhw */.
Babu mulriysy moy hu eliz ke suxusimw puos kowa.
Hea det afu qxasd ke jlibe kzikgp ri rbo gohop olao.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.