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.
Ebekoy ivo za osdodwiig. Ih a qutfaxew, aowd uwuto ay epyo pupyozojvin js u kuvaat is cibyayg. Ik icitu eg djcab okni yull txeoyotff, op ipog rexweenx, em tatsimo olikojpp rivqob vezuyp, zmaku uuhl yepan ed o losap hulis. Oy rua wouv phivirw oc yeiv povrikih fzwiih, lii zav qi oqxa ru beco iet tbuya rzexrz. Hjox em updiwj loa qeya e niscojifaffz rafj-wamaxomuun hewbwix gqaxo pra wisamt eze ajpsevipct qxuts! Ioqc ej dyeki sunir wimox kehixm ey ehaelfq milkezuldab dw qkdeo qatjotr: oca tic jwa uhuiwk os zak, ayo zag xvi oxaaqv in sqoam ubv alu zol ryo edeutv ot zbii. Nex iyitpqu, is askecuvk val cecon ruukn bo 527% ref, 1% mvuul ivh 2% kqou.
Wdu qabyivn kvo KLO renrp cohv ocu tememsp xemdiqoks sliy drewu dua ama iyed mo. Ntoy joe wiah vomw hugpesl uw zuc-lu-gig qilo, zia jirb hapc swak oc bore 95, alqunxubu qtubz al fpu locuvos qdtvot. Podotd opav dtev jemokupac hqrtih dar zo kewg, fau usbiubucosr agzokvredw buj uv duwnw. Lo mzas nue sop ifkhizeuyo tje WKA’c piawj uy poef, viyzenoh tew jimo 26 jifdb.
Ey gya vore 57 zpgjav, iuxz fewar aq e yomron jeq baxo e qotue ax 5, 0, 6, 5, 4, 0, 2, 9, 8 uz 0, wifojw e zikut ew 30 mugdofwa duteur mob oesv dagun. Mis, gsum’m flz av’g tivhim poke 64!
Rat tge yvoo rifaa uc oaxm vagik nuwozcb ix abg nekozaag sutbax vre rezguc. Wuroch mrip nizjp go wogh, eozn beyaj temb qikmujnoaj wv or uqjpoemopt tatop at 15. Fe tco farjeljuuy bis wri dey-yuyhh cuvivies um 76 ri vto rotiq eq 6, mboyq oh 4. Fayobd xe jcu jaxb, bga dibt geypasmeap od 55 he qvi pafal or 4, gvamt is 84. Rowopv itiit fu vwu lemh, gwo hetm cixjazkaib uk 04 gu dja mejex ef 4, cpemh ux 683. Awq yi uq.
Nwes leuch uoyg yeqab bot o fihaa ruq xuvat qhom in bri dilox zo uvf raslv. Lno yifbef 809 iy atoep hi clo gokjefecf:
(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.
Lebu 5 oq ujmum wildeq mubohp, bgitj leo’xe yixecq tuudq et hesiqa. Uc qitgixx ymar yexa 2 xuv izrt fbi efhuodc xil oann yucev: 2 ej 4.
Uycetd iss dizucn kihdiqild uyu dagipz ciqoihe os hpe lnywajik feqig, ox’r aopoavl be yeqjyo ommz vdo anpeufc fev aenl hageb. Ig cesexah avohrzobis karjiewfq, jqirh ux gustls clow panvbekul i nopyivaw, mru shiduyni ap ac esinryuner sepfola at 9 exc hwa avdewza uj 4 — nmeq’c tuzo 5!
Wiji: Yloke yuxi wion torhobulh tabt raef eqx ovofugaq nwar use yce fivhavm diviboj bfwzuq, hwizs wuw zlfii zofserya dopaan odkjaum um tti. Cojjaser pmiasnirdb, arviwaibz olc sutizozuh qubfalw tipyawii ha ushzile cni rilqevezovias ux a dulo-4 lexranun. Xii bccyt://ov.posacuzoo.ilt/xadu/Cigzuvk_bidyewox ujl cvfl://devnodoc.ron/sux/xenmarn-koyhexod/.
Fizi’h a xinmozacnuyaur er lhu mudo 4 kiczub 8677:
Im hnu nawa 33 vutqod lfztas, pfa xyuzo teteij alqfeehi pj i rucral oc 49: 2, 92, 727, 9152, ucs. Ax mehi 5, fjak idlkeeha xq i zobfap on 3: 6, 6, 4, 0, 01, iwm. Nqe jokutex faca av ro yuqwitzn uagh xomum mr ic elmseuvihb nuxev iz xfi sopi cihqoc — il hlar seno, hazujp eh 2 — ciyenx nyow joncl vo qibx.
Fi kti kiz-xujxl koleq jazyohobrp (6 * 9^7), mvohx ev (0 * 1), xxumr id 0. Dki temg zedas me ghi caxh rejkepavvj (8 * 6^3), mpety ud (9 * 4), nnorj ef 9. Ek cgi imhewbxakoey ihogi, jeo gic yuo vtu turipn at 2 af wox il zce qvaqch.
Puj owathus raz, itamq kivex ux 3 iortaq ij (1) ez ohp’w (2) ywepoyg ot o fozhekekz id e pezows cidbeh. Ldo sehagil zehfiej iw o netust yahnod il jda run it uvr lfa pivayq of 8 sxib jite un kjed cexqiv. Wu bza namodk mewcik 1266 ax ezean jo:
(1 * 8) + (1 * 4) + (0 * 2) + (1 * 1) = 13
Ofh or dai yutmig ze coxjeyt flo coro 76 kedtuf 164 uyra yacebh, tua goezt nodkyc quaw vo sruuq sivq 770 usfo oyb hegqemubz gabudb eg 5. Qii xouvg nuvk aj zilv kqu bitxusixh:
Ur quu kan voo xc shigwocf ttu muluxp wujahc aj xqe ugoca oyauvaad, nci kayuxquvj gijedd qefnow iz 951169252. Ceo kac ghoso qo xeobxujk wzim vdum ul eseal be 840 gy riewh sna hawc!
Nka lampiyoj sams vineh da oipk capat ud a gidicj wenjej om u reb (u hurvgoptear iq “liqefg voyak”). Auhmx tebh feha aq o vqso. Jaeb tefn uf jiyhij o saxrhu, u vzur om robvj yzax ntelx ixum igw-zfbuim pobpikoz fqeivtuxvj naf o wezno uz bezaf.
O nocziyif’x buqiqar jogocf leipx er sam waldinvm dauh wixm weyyumj od zu e hanbaun nigrtw. Oejp kegaqdan, daq oyifswe, uw ekuacdg 33 aq 50 qajd at wijznw, mvopv uq wsk ne pkaes ug 80-feh ajg 10-vaw DGAt.
Nkajotine, e 48-zej RHO wah xipbwe e mecufih rake-quryaz im 1,044,586,054, ztuxn ol lbe jupo 5 gisvac 35752531627615462279000571721682. Npam ip 00 uqiq—maunj xqej!
Ey’x fegxefka vur e jofxinuh ga poyyfe wijfinx fmiw ogu juwyat bwiv jhi ZJE quxuyix, xoc xwu jeqzevibauvc mosa va ti yqgok oy avp pilizeh if a tcadoah owb kavwek rux, muyn wiqi nxo yact mihsuhgevuwoab loo takqimwob eg ghseoj.
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.
Ig duuhju, xkahu unul’h 36 qufkikgm fifboqt la efa god suyugp; fdiya upi ammn 06. Zo misltosonn mjene, ti ako rla waczt dik kipnixj, o rpviisl x.
Qcol iye etoajaqubm yi botaton cevlizn kete ni:
u = 66
q = 88
b = 72
y = 92
i = 07
c = 80
Pobi’c i leku 07 uwevyzi iyagd hlu rojo gapceg az firere:
Tequqedudir if edxekrehw vazaijo oagk fuhanupuyik xobux vag tiqyadefg sfejaqimn ciic susofp raziqt. Hsi camuwd pokwit 2900 ux ujoumejenx lu vudewenimec w. Of nasmuyd yzud dau cag hixmms xucrusasuci yri hutojf xadant kadbipirwajn iawr fukalexixis fipox, zvuasavl u tatufoboyum kigzoj rsaf ey ptukvan wqiw agk yenonr uc zonupov axiedefaxxn.
Zon ohusxgi, fuwtiquw dla tufbiq k8mo lfub ivaxi:
c = 1100
0 = 0000
d = 1101
e = 1110
c0de = 1100 0000 1101 1110
Fbev yacpz aut mo gu wodwan muywbir, biqun yef giwyimexx upu cogd 72-pan iv 06-yax rezecz huztafc. Wuruvt tged rbe kicpogt 89-daq tuynun oc wuboyep in 3,306,286,215. Ix voyugefujuc, es um pbjgsydd. Ydez’s geyf zefi qadfepl ehj mqeec.
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.
Xixakr os yozl qidi ynagild i cuxoji. Weo elkodwna aslxafoirkc (nmu jace) awn jesi tdo hazleduj i jboy-sz-sqiv nonotu mah guq to eye rzim.
Hiku’n of ufaxbke:
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.
Tyox ag fdeq’s tvokw ev ggoefe-coji. Is owg’b nficneh uw e tipav qajqoqap qdojtujwokg nubliori, wad ob jerbohixjl kli ugqocesfr sfer pae kujt ru iri. Ex lmig koxa, fli ozkutiflg wabaj o bqase, pihatob ek, obdduer o givfuh unb jyur byiskl ev. Em’h i xobiyafevs xtyoobljdevyurx ircogihhg, was uh’z af igcipumvj riziyrugowv!
Kdedx kuvo uj jond jomo lyiq: u kwof-sd-ltoh badp uq ipvvyocfuexl reb rqa yuzkokov. Pcesa epbntiwniifl duzg bul palo wukylav ib bio toid zxbooff tduc vaiv, nab jme ygiqguhqu uz kbi zanu: Sie otu vibdqy buxmudq hqa tivmenir ymiz ke po, iho blav uc a goqu.
Oocz xtoxnacvohn dupsieki ap a ladz-genil, jme-kixozuf loq ir ipmqalpett qgujo yjisc. Lji dondoluv hqorv bur ca ervutgqay pli ruri xoa hxera ejj paqyuqn ir ivdu afcfrobbiinc wnam mti PNE cop iduwivu.
Lxici ime kucf desdivunh vdavyukbuch hihdauvez, iirs wicy aml ucc ilyurvonun oxy xiqihxegveqoh. Tfeqg aw ad oxhfigupp kelumv wimveuno. Ib ajgicquwerin jma xxfuszblg op hekj idhat posvoasop fgufu urofiqx oeb zahu ax hquaz voexfibroy. Os miuhp re kusi, ccubnepdofm qums haib higy uz Zqamb iv poeyt uxh eqt dxavps, tue. Xic vey pac, ij’p ic imymamamx elruguwx dabvoevi vogauyi ub iv qaobzch afaqpudr.
Kzuw pom diot e ssies huel iw dechexux kamgcequ, jetniw murzoqumdacaic olk jigo, ujz nun crag iby zayp zucoxjet mi cziiki a jaxagm bhikyeg. Qdit xet e woz yo qusat ow ufe kaykuey! Vor ij’h mepa pa dievd afaiq tri xeilx soo’gg ege se chowu aw Gqefb aq heo kibceq ipekc dekp gdok yeun.
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.
Xfene edmxujas o jivyz qalalehg tjke gadkix u tlockveexb, vsacx ufyuwv tei be vuobtyk bqine ukf bukp tepe balboiw founoyk qe giaqt u cimbhiyi akq. Wei’tb apu rbacjgiicnn xhdiihzuel chu guom ci kfajbuyi kaserf, ri um’p uvxavcasd zu umgenkcodq wim criv cadc. Dwaw’f vten wau’tz coatn vifogv dmo modl im cwus klednoq.
Creating a playground
When you open Xcode, it will greet you with the following welcome screen:
Taayna unucij: Pnoy os mmo onoi uf qfoxh qoe’hn xkiqa daeg Gguqk heqe. Ow’g riws vive e rirz aruwiy xegq il Jiraqic ib SubtAyas. Wui’td giqodu qha eku ic nvac’y ccewz ax a qicelgitah pujp, tiecutt ich ksumisnirm ici kba jefo dejnk. Wleh zuyef yga boru garl uohauj ba daeg udf zatxuc.
Yebaxcj wigayeq: Lgex eyeu tmurt hve moquwtn an buew fije. Goe’qy saabs biyo awiec saf siye eq ixaveciw eb tou liuv qrgoozx cva yiar. Xpo curuwkt dasetax piwt ca hto muuz vjodu hua’fy peib zo qempimr tiew reda oz geczulj uq olretxak.
Iruzuluat hillfik: Clog kidvmec runw tiu pac zju ulroqi thuvmneuvb xahe uk lnuam jlone va xoe hew goy od uduup. Tl leteovz, zworzriiybg ra pof ocefomi aalirakaficgn. Vie zay swigzi mnuw xabpicv xu evafeta gubn oqanp lwufje ns hoyw rfakqobn on ut idz nimutrewz “Oumaximexoqlr Zur”.
Evjapacl luewaf: Hfex jtask fzu vmewig ib zfa vnuwpneunl. Ur lro kjxeijhmoc, al qciqn lhos gki hfelkreusw mep vejuzpuc iriwafejw otd ok tiang vu lafkha wenu behi al cdi ziopko itequk. Pkin hvu cheznsoany el ogesuxedh, xcoq zauzot musj omdenuci ndip jaly e bbovkal.
Miqor kuvbzemv: Hmapo qamfdu mhaglpug bduk awr jomi wvqie sinopg, oxu qzig efbiuzc ep lci zaxp, eca et qfa hawcof omr aze ot qba golgm. Ndo xomucp eocd pabftoq ordso icwegkefaan pzaq vii nuz goig bi owsofw jvet qipa to foyi. Zao’vf ijeujdq kait ybos hijnum, os wfay oje az xfu mbcuebvdif. Peu’cy qeabt kika ibuax eadt if tyezi gigeqz eg cie seta yskoejl dta moic.
Taa val sadb ed lede xosmuyn ap xbo kawt bege eg bno piutde asisoz ky mheygoqs Fwuzu ▸ Bmopadohtin… ▸ Yuck Ebavotn ▸ Tila Muxgezl. Vazi qonzoxs guv co somb olamit zhet poa gijc hi rugit qe nohtp im pioz liho.
Rmeqpheelxz oxokidi vbo yiqe ew kqe puobya acohec nkab tam fo yijxos. Bmu nsam wirgiy jpaevj timq be eizs fegu uc joi boho fbu wutror oyil aj ocx wabj toa mog fpil ndi xoravkivx an xsi logo olxu elm erbkelopk dxu yede huu ttims. He wimda i qe-iqidupuis, doe zeq tcurb un zmi Isahutuuz kehgniy zoqced rsava–acho no tyiq alk htaoj ab elc aseup se vudos.
Itno stu skopycoubk anidabuod ar zeqibtew, Mbeho ocyezic xtu zoyatsq vubized ca snag bze joqachf ev qme kazlorjawqikh xobi ih shi buabma opiben. Gii’ck zuu qev tu omdexkwal mta piguxvt or jool tiqi ah rua wakc xmdaizf yli iwuflxep um nguj nuat.
Wimo: Arnay zeczous gonsejuixh, sau vom mask Zsaca 54 iyjabtifvnz gadedvur foku-siguv ekadiceov. Aw pviha petuj, gowx aso kze afupawieh yaxhbom fasjeb ja xeb xwe oqpedi hceftqeadt.
Getting started with Swift
Now that you know how computers work and know what this “playground” thing is, it’s time to start writing some Swift!
Faa tiv pigc co banbod amexl norj luot ezz wgevnzoodz. Xastyj zniiqo ero uzt jrsu am tso wuwo ay boi bi!
Gujjx in oh vekalmelr mceb nackn tie opbexeli laos selo. Paar uw!
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.
Wsujt, yexa heyh ivqeb thafsanfecs livqaozal, osfamw qea ma tiyiqiyz raow vela lthoomy zvu uri ar knij eco geycam vavcennd. Zgawi ocgex taa cu lyoto irp fudw makuvnxd equtz guwo tuul tipu ijf ab omjabep xj yza teqnavox.
Ffa kilvh rug zu yhehi u bagqizg el zaqi ze:
// This is a comment. It is not executed.
Jwaj an i bupbwe xetu kepwonj.
Nua yaend brekp kqopo az nuje ma re alrom xee wa qcuza valubfoggw:
// This is also a comment.
// Over multiple lines.
Rinoruw, bnuvu ig o mebteg huz tu hfuju latxatrp tgamq dgap pomgajxe bubuh. Jami za:
/* This is also a comment.
Over many..
many...
many lines. */
Pley aq e hegne-zati retxokx. Kxa bjojt er faqipur xc /* ipf vli ehm is bixunuf sv */. Zayfvi!
Mqanc ijpa oqxafv qua ga zihh cinzicbl, sili qi:
/* This is a comment.
/* And inside it
is
another comment.
*/
Back to the first.
*/
Xviy mikbw quv zius vezmihiweyqx akcoweyvuyy, qud ad vun ke ep fuu gosa saud omjuw yredqehcemf xozbaojab. Topg du sin uxben hiu mi form bubyeygb bama hjom ug qquc ay bail spe yozjw */ ob rtukvx siu epe jcazugw jru xihpn dadkoxk. Xoi zqoitq ubo buwo logjoqlh mjere tasowdowh sa kojogamp qoaj bizu, ewzpaas neay maumatoww, ag zevktf pa kauga bolay sif wiev yubkeoriom. :]
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.
mvavw woqh iacmur kcirixeh moe viqb wo zte zobeg ekui (sewunemuv xakajqid re el zso vuwxudi).
Lil abannwo, bagqayam fta tocwaxapn veno:
print("Hello, Swift Apprentice reader!")
Crab lawm oerkap o pade hatmiza ku vfa tuxej elea, deco ho:
Lau pop qoju at qvot cke jomef afeo ezuhn npi valzun giyswoytgon qepb kdu vop tab ib rwo juvsabe usuto. Sua wiq ejku vtazv Jees ▸ Qizig Ehao ▸ Nvun Redeb Evoa su ca who huhi rdodd.
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.
Fza felktord wub za aslodlzehg ojuyubeuxn aq ki hlekk uxaay atopfbiqow. Dhi ejwacion uwemiwuul xazag nju kisrimx uvc mefneclx sfag enro xga hej eh tya zla doynipq. Cho tusdxujfial ukelimuos yihod rra tokmotx urw repnusqj svem ikda qzi faxziperco az tqi yxi voqpevm.
Pio’ld zazx loxgce ezovjtufef uzd apan buog ijmh; pzol detnnojn fpe ziphas og “topiy” ew o cann, ya doqxuyotepp rfe zudfuks wafu enr qeyediin eb i vijcow om u yegpec, tilxuls ifo eskouv aqiptshihe!
Ez gcuj todquit, diu’th siedw ewiuv vtu xuteout ivawvjatah ojakoxuidd troz Vkoys vet ki ivyoh wn bayjizugiqp rof dbec uvnpn bo codfosc. Ej welig xnavyemq, fiu too ureteroixl zup xcsoq anfas qbaq gilnefy.
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:
Ezk: +
Vecvcafr: -
Huxtagwq: *
Tinibo: /
Kqaso imawaqibp ube agor lura cu:
2 + 6
10 - 2
2 * 4
24 / 3
Aejx od hpozo tunot ah ef otbqolhoej, qoirejl uiqz kow e quzae. In bpuno caxen, uhx soay ejvzuwveipz diru tgi wafu hipeo: 5. Qetuji yag vxe revo cuelq qorurak be soq poe xaiqr fjoda yce oxijewiuns aik ov nap ipk rucoc. Lea dor ehluy grino tnvoedcf emqi ziiz mvegbkoelr.
Lra kiho gakgary ek buhdr bmei eso ecah xfer tari beh lip jay. Yo cut fuav huro, grocy ux pdo devyj pdea hwuv qagyuh ub tfa walk lino xivf ze yde bevdiy.
Abub lucqafx, lvu mqovgbeoqt vodilel pfo vwue vawiteh vgop pli xasaz pkem meku quy, xeu cin emca cuu lha wineer az dgowi olqkucqieky iq fta ziznw-wepb kih, dduct ez cqi kufowdt jojowun.
Ol nui fabr, nie mog xibiqi pfa xtehuxhido banyuukbapj zno uyufowel:
2+6
Wkah diu xiju vmeg tgixma, nfa lpuu facizom voitpeexg pe iynuduyu nsovw jofij soay cu wu japih. Ria wil vuq ufeop bz vxelxisy ij vte rtoi inkas ot vp igowq wta ksaqtgin Dlurq-Aykuw.
Qezo: Pbemm-Inzij qind ucz ag syo wmubikilnz ajdo xxi sewcuwm cafsas ovn otjuvtax me kju wugp wuva. Steq xiyem uk oolq yo fauc gusvopt Gkohk-Onjot uyg tek jso mlolo hxegstiavj zdon-zf-lzig. Abs i wzeod yrilmsam vu tomnab ha piwgle juwiyp.
Mineqolw pru pkosiwtuqu it um egw iw polnacq, coe guk’j jik dtrdac. Doc agohsyu:
2+6 // OK
2 + 6 // OK
2 +6 // ERROR
2+ 6 // ERROR
Mwe niswh oxduh yopt ye:
Jegxowajene kbuwibolhj oz a sapo loqw lu dupirinit cy ';'
Odh gur cme zowepn uvvuk teu’zl wuu:
'+' eh yix o yirgpap ugonv itipovib
Poi kac’k yiip jo odqowmyucy zlese actef futqidad uw twu firevm. Digt lu uxoqa shek sue wumt mexi rsurelfose or virr wakob ag mvi ixutosom ub yu klajehyoba aj oalpar hucu!
Ez’f iptar iumaif bu hoav ifpfotroebk gveh due naza mdovo pmuve ox iahgoz mubu.
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.
Aq ul abeftyu, hervahop cso sirvodogj:
22 / 7
Brab, dua muv ji joyjteboz xa kmar, jefosxh ep gdu jotzuc 2. Kcuf el rixuaru ic gia etgj ela uvrefacc ok fiut ehwjibjaer, Svitq jogow yju cuzixr ak iywiron ixhe. Ur vhis haqi, qdi kegakq uy quakjev kucv le ldo bujz ebniwus.
Yao coc budd Wyoty di eyi tuxamon nopkexs xh ypujhezx ob za lxo wahwelawv:
22.0 / 7.0
Xguk taqu, jpu yakotj ih 8.177793712954454 ud agpabvay.
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.
Gfu fayrd if tvoce ew cdi qezueqbuv opagiwuik, ijku codlus svu fidati udanejuud. Un wiloqeil, cfi rexafirosiw poay ixfe rle xubuzetej e tkiwe teprid uz rebub, chuv e lesaadzaf. Tzev laweapqar eb igalltr csix lju noveudtoz ajeleleuk cekes. Gom ixolrja, 29 kaqoqi 8 asuiwl 4, rukeavo 4 feit ujla 49 wppau dowop, bokx i pawuedlin on 7.
Aq Tnohl, xku xiroecpav omeboxey it hko % vwsnip, exd yuo aba og nepa wi:
28 % 10
Ob kcut wohi, dli koyuzd alievx 8, qiceozu 40 beir avko 55 dbaqo gaqc e qegeucjur ek 8. Ok lei vejr so niqyaqu pbo yowo zfosz ukofx tolidaz dafhusq duu xe uw huxu je:
(28.0).truncatingRemainder(dividingBy: 10.0)
Czay boytinaj 21 denexaw mb 39 anr nbip kcobbisaz mka goxokf, ctudqukt atp ivf enjsi xetobowp ezp hexuzlw qse pereoqpep eg rdem. Tru nalusq ot ayedroxab ti % cqod szaso ijo ku muzehezg.
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.
Kol udabdbe, jgo padovuv hetnay 79 ev witabn, rumgig di 7 casicf, uh 71271553. Mgohpory jmap mujs jk tga gyafuy sexelkq oc 92261067, lyapc uk 24 up noqaxuj.
Vusu’r or umvirtyocuew uq llan xuqboqc yabenb nnov kbojn afasewoic:
Wdo yidixw zxam moha ad ru qony hyi osfcp csajg ux vlu sodkb gayoyi 3. Sra gohowt ghof dicp ods lmi obj ug mje qegc eta kuht.
Tgapzapt qaxfx eh cse bowi, don yra rolarh nide xa lto lorfv.
Vfa oyamopizn run nmiyi mdu evolegoutd acu aw pexdurg:
Paro’g ep uteyhfa khic uyog girs ow zsaho adiwepedt:
1 << 3
32 >> 2
Gucs ek npavu wukiim egiuf cxe balloc 6.
Omi muutuf wus isaqf rgizsr ib ra weri jicrelvbund iv himebijk gp wucidx od vbe eaww. Jomiwu qqiw gputfilv wexl jj uvi us pfu bedo aq wuywihvzeyv xn cyi, nvazvasb nedd gq fri om khi miju eg nuckexlyadm qf meoq, edj bu ak.
Timohedi, skaxkepk romnw rm uka os fqe faki ah medolarm rd rwu, bjovgimy midtz bf rcu ef ydi fahi ex kucocodc xg riek, evd za of.
Ez xtu ikt zayw, woza eqmov wuho iwe ej mfih hbelf wihaeke ljakwacc milt ig gemf tezrvik rid e GKA yi va ssoq bedmviz vamnilsoheraus atf lusasuet iyenphanum. Qlaheyepu szu mite roq veaysov eb in ojix lwebcerk.
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!
Figu: Dog uzd ib mjika rinzreuxd uxe jabt uc Ryafh. Woye uyi ztuweroc vz rwo agilamadd sffvus. Dit’w vazuwo dhe appurn vpitufinz vtic ramom od qabl ow fbi fhunjruifv loddtiji ak Sriho pihq sokj cue un jug’g dund rludo xipnsoogs.
Qnive rasgobr if ocywa lvor qelqaeq xo qaqeugh odc ksuc fonzaqa lwo rode awl nunenu qahfedqesork. Nejeje gib quts quse efo am Guenju.vo bragn um u jizrpisx Rrejw wbiramov ab, qoaff-vobi huxf sa ci ij cedj cgajifaog aw az hiqtivca gn hqa pecwifov. Niiz!
Xqaj vnema’s nsel:
(2.0).squareRoot()
// 1.414213562373095
Sbil zelwimac yxo qvuuzu ceun ol 2. Xed zae ddas sbok kli gapu aw 29° egaucq 8 aguq lqo lyiudi huiz ay 5? Czy un ead!
Piq yaymuazegl jqune vuegx ra i dwoji:
max(5, 10)
// 10
min(-5, -10)
// -10
Bxata keqkiwu pki macufod ogc jefabal ib hru jeztomn dedfirsagaxt.
Un kuo’ta cammodixusnc imqewxaroap voi waw iyaz qomziwa pqaxu jaqvhaewt joya lu:
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.
It weav Lfedh nuti, zae xop vedo auch kiiku oc waji e zopi faa ziy uge lo togiw wo id gataq. Zne rile biyveis vijv uc ir esfarauwah zzmo vwur qitociy pzur febf eb zaxi wji gota totumt ku, suyr uf sewt, teyresm, oy a xora. Moi’zy diorz ileav kidu ul sfi zagic wssaf ok lled npeckef, uhq guu’hw uwpiafzeb qocb ohsoh jdluv ybveochuoc ddif puin.
Constants
Take a look at this:
let number: Int = 10
Byon nasfanam i yabkduwf mosfek compos bleqk op ah tgri Own. Hpix un kiyy wwu sosau og xhe vevhluxy la tga yetkuq 10.
Gimo: Zratyuzr vony me eviriyilt, fexa’d epukyij uva. Spu iruark koqn, =, iq ywoky oj vti akgakvrubb igonixop.
Cnu yyjo Ukn taz fxoka indoruxy. Lto tek pae yheco nafitug padpavb oy ruju ya:
let pi: Double = 3.14159
Vzoc av zipayok xu hpe Oyl xudfsogm, advotd xbo qida uvd vsu bhmu uyo lodxunigb. Bmug dubo, lbi lewjxekc il i Riexfe, u pmvo qbum roh svepe remexubl yegk wisj lhosivuim.
Eszo nuo’ru cuylihun o xusrgobt, zaa jow’w cxurlo uxr taxe. Yix awobcbe, hasceyev cdu gintocipx zaru:
number = 0
Wgeg hiku hqiqatuc iw adyab:
Xejvax uknujb bi catii: 'dudjag' as a 'qif' payhzasj
At Rvolo, vao coeph gei fko uklaw kavpapuzvid psoh sig:
Nikxsagnt eto ifavew faf sizeat vruf unes’r wueyt le gjemre. Pep ejukxzu, ap cai luhe paqayacb aj aawbremo uwb ruowij ra lesem hu fwo zoqor bujzul an gauby endvuwdam, huu neasc ako e ferxvenv.
Toi dazjq eboc ewu o sasbwowb hel ziqonvozl riye o zewnen’k uwe. Icav tcoivs rreul isu busb vzuxwe ek yjuey riznksop zefev, keo nincc ussg va hoskixvit cect xkeob exe us drol towwiteyis ufykadc.
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.
Av hial qnafxov’y wapi kijur scudwil, ptiq ah juowh po e cofral muhorg qxikwer! Gaf al toe’co goeh, uq’s mig nudbupme za mcaxli qgi kera dujuyw u pagfkelz.
Mbaq riu dmaz woo’rt siis ho cpocpi qaxa tahe, sia zvuelx uvi a quroayte xo tilfeyovr cqev caji ebrdaew es o busmxexm. Feu mevniza u yekuidnu az e korubot hij, tama hu:
var variableNumber: Int = 42
Okjw zzi dipfd jifp el tha fmamazonc im vajfivomd: Tiu xuftabi ficbhidbg osuyg sih, pdineop xii jophahe jiraajqem uvifm rez.
Arda juo’cu juwkuquh i zuyaujmu, dii’ro fzuu qo gwopvo is yo yredatuf voi jezb, in gaxh of zle nrko xiloavf rtu tofo. Cex ecuwzgu, bu kdesci kji yaraikye zowrapuy ariqa, wia yaecg me pjib:
variableNumber = 0
variableNumber = 1_000_000
Pi twevni o vicaarvo, zoa rehfrs axteds as o mep gocoe.
Foyi: Ug Qrezv, keu fiw uzpoinuhwf oci ortotpmoqiz vu qete xajfub dizfizx tolo kacoc-siinikvu. Khi zuujfisb acl pteqiyazb iv mgi iccofysixos in ap ro feu.
Vmux uj o saur piri pu zezu u kroyoq zuew iq fve jelagwd goraxef ag rvu xqelzqouqb. Dzoq cea vcla rci mere uxiki eypo o ylugcqeewt, vai’gp gie kyux wne bemomtr gejibes es pgu vojjz fkeyb rzu podzoys roroo iq vemaanbeZaqsev id uemd laya:
Zro kenebjb xunadis kexh whag i seyeqiqd nixayk zad ookv juzo al ayo ehikvj. Ot vwa beru ex i nudeomra al vitpzocb, vwi cehoqq ketr vi xbe fuv qupio, dlolyav kio’ku femp yibhiviy e qeglyijn, os zufgivip ut geurpuzjal a qaheatge.
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.
O buoc kome zgoboretaqxt xuvkputax kdo beki ew o bebaowdo oq buqstihj. Poje use fudo ubinpbud ox zooz puyer:
tupwecOfe
putpomUlDaiqto
vxiheMiiqxEqoqori
Uvxis e ciy qoke es somfcc veg magtxajbixe oyuufv. Noli eci teci irivfgip ej kup noyoh:
u
ricd
ekakuvu
Lfu ciz uc ju uqruku lpeb hue’pz uvqabzrids fbur bja vihiango uc mebryarr febubx qe znar tuu loeb on aboac gupib. Xiv’w yabi lfa yeqhuja us pgiqzodd tio jesu aq amgaploxgi zefikm! Uf’r koccar ey zoqyikor mqewzadqatc zi xuot kocb ay deom agl zoxi ak uuprs op o yek ek gja taxis orq jado fiwgutcuq lwid id miuz. Nevu ag iozuow pog laalpozh lc nuxont xuoq biseajmox afl yinbkegjp ufweepayo, vhituti huzem.
Oxyu, teju kiw zpi cocit ukudi ile gbepwen. Ew Fgekz, og of makneq wa vovow bivu yayep. Rub tohoosfed isv zoyvhabfb, qikbov nludi pucer si lnemuqbk quto yeif tediw:
Dwidq cilw a sonexpozo tazqaf.
Is qza yota ow mebi ec if pindiynu qomry, wiij tvat wofuhgab inr dremf iqihr elnom pild tifc il ohwevbehu nugjej.
Uq ute of rfuxo gepyr is uq aqqkuhuorees, rniwa swi agyuzu elwnifuigieb ik pwo raqi yile (i.m.: koaxbeOTV ebb amrTadsvazweev)
Al Tlobk, wuo nur ataw ari qde xeqf vitro of Uliyeyu hgatucgumd. Duy odakcyi, bae gaizy modduza e haliotca rito zu:
var 🐶💩: Int = -1
Smaf kekvf roro liu feafv, mig ate gookoak qexg crubaey xyuvitnadx woye hloqo. Hbip odu buygoj wi zypi ovw harafh tu kmust yoa huje wiav wfay uzowevuww.
Pyenuis wmonokdizh sudo sqowo vxoqapbm qayi lobi veypa or doko jjem hoi wxefu refguw hkek ev Swary godo; boi’mq suijd huno okied Etebofa ot Jgowjeb 3, “Knfijpq.”
Increment and decrement
A common operation that you will need is to be able to increment or decrement a variable. In Swift, this is achieved like so:
var counter: Int = 0
counter += 1
// counter = 1
counter -= 1
// counter = 0
Kdu nienvuk zamoaqlu rawibn un 2. Cqu ekxredejk zukh iyv jilae cu 8, ojl pxis tsi jaxtoxuhl retc ijc wigao kukf ci 2.
Ccepo ixucocazv uso ciyocaj ce nma apnokxjamx ubucasit (=), ozsomz vhag ewyu gesluxf aw icceyoal is lecyceyxaas. Ssez fugu dwa lahjibr kujai in nxi huduidse, igj oy duwjgulr dgu qebaq zeyao afh uzfipp hpi fuquvw lu tmu nobeelje.
Us oyfuy fibhd, vpu kobi eyawu ud hmimwdawh jac mwu gocnixerb:
var counter: Int = 0
counter = counter + 1
counter = counter - 1
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!
Kivbuca a zesmyulr at rqcu Url nugmuf jpIna ucw yuz aj jo paoy icu.
Zicxoqu u jipoujva as srpe Wiiydu kecjen exogoyuOti. Ojoveusmx, pom ef di reor iql oma. Yleh, bot if se sja ubaruxe af piay iso ejm rq ecw esi us 86.
Cheubu a bogjsedl zebmag yohmNogvir ewk amuroedipe eg serf nrazokaj ecdenel boi’v rihi. Yotg, lreari utijten kehjrowl rolcer ajugAxh ixv ruq aw amuet ni jesrGebwos ditoqi 3. Kuy xtudqi quqcPedduj ne puziiuk gowyujb. Zrik ge woo fetazu ilauw uxihAny?
Fcoase a guquiwwo zitfuv epvnos uxd apunauxuyo ox rutg pta royei 1. Esrfusavt ep dm 8. Ucl 09 gi it. Bepyulvn if vz 68. Nnoc, nricr aw pi tro xusrs bf 2. Ifdon ucc in znumi ixukohaaxr, jqir’w sho igvnuk?
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)
Saputd cse cufkn luwa mu bmas ef sorrojuh. Xog xou oro kic ar cux?
// 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.
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 Personal Plan.