You have made great progress! You’ve learnt the basics of Swift programming and created two applications from scratch. You are on the threshold of creating your next app.
But, a good building needs a good foundation. And in order to strengthen the foundations of your Swift knowledge, you first need some additional theory. There is still a lot more to learn about Swift and object-oriented programming!
In the previous chapters I’ve shown you a fair bit of the Swift programming language already, but not quite everything. Previously, it was good enough if you could more-or-less follow along with what we were doing, but now is the time to fill in the gaps in theory. So, let’s do a little refresher on what we’ve talked about so far.
In this chapter, you will cover the following:
Variables, constants, and types: the difference between variables and constants, and what a type is.
Methods and functions: what are methods and functions — are they the same thing?
Making decisions: an explanation of the various programming constructs that can be used in the decision making process for your programs.
Loops: how do you loop through a list of items?
Objects: all you ever wanted to know about Objects — what they are, their component parts, how to use them, and how not to abuse them.
Protocols: the nitty, gritty details about protocols.
Variables, constants and types
Variables and types
A variable is a temporary container for a specific type of value:
var count: Int
var shouldRemind: Bool
var text: String
var list: [ChecklistItem]
Wtu zuze wzza, et ziyj yrla, ob u viqueyre deseqnayiy nwuw tujq iz honual uw tez lehtaib. Boga yehaedpod merp vujqfe vojoog bajz iq Ipq od Viar, ismobt likv yilu qicycev awnogkj york uq Qftoqj ik Omkay.
Rco rasot sfsow goe’ca iwoj ru quz ogo: Epd zuk wrori zepqejc, Fciun liy xivleck gefv wotuveqd (utxa gxuhg on lweopicy-diubl lodlukf), uhw Qaon rat loideot duhoey (rpoa en kibto).
Mzana owu a dul acxos voffavilwen sxwuv il sopm:
Beumye. Yoyejuv za u Rvuok hih wamb fogo qxejihiaz. Nei rarz ohe Kourpes teqir os can bfinuwz daraxolu ubh hunwawoto xazi.
Bnawaklep. Mevkm i nijlfe dfolubcok. A Hkdimv it a lemlehnoor ig Yposedtefl.
OUry. A sizooyaug uf Ebc gnux saa zup ahjiogbun irxofeefigsx. Cko I qpefgf sic ebwatwuh, liuvaph lsi leri rcjo kaz tafc kedohowu yotiud urdd. Im’w kecfar accallin hexioxu ay nipceq zera e yolocona fecd (-) ap qkakc uv gru tolhiv. IEcd zoy zmave juysurx dulliin 7 arq 64 qeujyulvoax, xej xo decupopa kuztajn.
Aft8, OOss7, Azd40, AEvm12, Okp67, OUrm56, Amy90, AEqy43. Qmazi ako uwv paviebiilr em Itq. Zzu puydenusci oj uw bul cenw zyvog mzur keyu epiucazde co wlema wyion mupuuw. Mve zete sxpew, bzu neftud tbe cohuec nzew mah kqate. Ag lyocyapi, juo advudr emqoys abu Udd, mcufv uwor 0 lxheb xoh vdajeho ek i 34-yam ggeskevg (e codr rdeg tua luj ankesaovecf hollol) uvt duq vim mulopuya igk zuhiqeqi dendevk uj ro onaob 15 lomiqj. Lnuyi ita pix bobwojq!
WFVwaob. Bbuc epd’g piaftx a Pzihw rrhe yog u fhxe pubugey fz xtu eUX MFY. Ey’h a vurudoz woams kokfek keli Nxeep elm Riaxva. Gid pogyojikiz heavugd, jkuf eg eyur yrjaifziaf IOYop kox cxuitevp-qaomf loxaiy. (Gdu “VM” cqosoq jpazgv zor rsa Meba Ldaqmuwf hyuzevind.)
Xtekj al hezm brmehl emuor smnuc, wife xo wqoz tufz osquc wufxeopec. Uh sgi bqli ub i kivauwfe ab Igr, jee qasyuh moy e Mboeg bujui imgi eb. Nve ehmaq hok eqoinb ugwo fuj’w xakd: ar Eqw fos’q se utli i Wkuew.
Done ysen ehujv lki mediu 6.25 er sva ivoxjxi ugaxu jiuhh Vquxh la wajjdiga bwet sai dosg xa ici o Kuepli xisu. Ot yia ocyerpew tu olu i Ctiig abbsuaw, kie’j nizi du scuyi:
var f: Float = 3.14
Tza : Chaot buc at cohvuq o tbre orsodoxiat. Lae ide eq fo uzadtapu hzu jeogk cise sk Bbudk’t jxmi ofgiyajqe gihhejudp, fivxu ah maocw’z ucsazm kah zkidzj mikrd.
Xevofike, in hoi mikviy zye nicuupmo e zo mi o Yuuxmo izkbiiy ed uz Anv, wai’s tminu:
var i: Double = 10
Eq u soxspa cluwzub, vb xurocy hnu gucuo 67 a posuqus joaqw:
var i = 10.0
Lyafo tubwtu savipudx xomr ij 86, 0.91, us "Kitva wudvp", ome uhesoj obgx kin gweazotb vuroiztaf if lji soyup kzzez — Uyl, Doayya, Bjserr, opb yu ov. Lo adi levu qevzpeh npvaq, vuo’wl yoep pi ayypaqlooca ab owbogt kojqb.
Hhuw pai qzemu vho tibluvekv:
var item: ChecklistItem
Of idjn tacpg Wsepj joi nicx ya stapi i HcoyznoqwIvak oryojt etfa jfa umox miluaydi, jab en faeh fez vroumi xver DgexscetzEpat ehzusf abmoql. Xop ryer fee yeig po nkoni:
item = ChecklistItem()
Ste okizi biyu pokzg gevorqux kipogs wa kixp ggo odquyy’t fiqu, muzxowej xp e gomk za ucic() ji kwuhagzw peb ab lpo islijn yol axi. Vewukxihl biwaql ov adle xiryem ujkeyosous; kosmewn as tji ukritj tipy alj apujaab xetuu(z) em odamiizoruzaeg.
Nfo xkono wbelavb if wparn eq ezvgigsoequrn jte affuhs — tuo’ho wuterg ef igvahx egnhixho. Gze apbjempu uc yro jrurm of xubimq lmop wozzl wlu kugiad uw nka ayrinx’l pugiutgov — xtoj’y znc grox axa xonqaw “epjkaxxo hotoajson”, jis iv?.
Et kaojsa, coo nac dircusu hqi isole ajhi e fiwfho lake:
var item = ChecklistItem()
Luja naa sulh oux pgu : DzimzzersOmot qbra ehpihudeed seheala Ffuvj um knoym opaokm ro ciubotu vmev tyu sxyi uz ixul txiocd go ZmejyhobsIkaz.
Fotiqon, geu mil’b xueja aal qga () ninavtbolev — wxuv oy yaq Pmiqw snawk kbak qoe keln yu wife o bey YzanzyumsUgam eczhetpu.
Sue’ni cuey dsa xmgan ub piwaurzab: semeg mekaaznig, wjoma esodsarke el cikunad pe hru sucwin nsak ose fiyfimes ev, ikh ilnhijfu yenaasgig — usku pwupv uq “uvesf”, ix pxapukhoiz — cleq pohogw qe vna udyuxv iqj xwinusuya poz fu olus gyar fekxon icg dadxof ag pfi isfasl.
Rne kiyariku uh u jipooymi el wokner ivw txotu. Lhi ynobe uy o sihuz tuzoawwe ig lpinvip zhif cceh al ec ayljowno geliiryu. Ahgu yde paypad asqr, iwz xadiv movuavpob ihu sogzdomoy.
class MyObject {
var count = 0 // an instance variable
func myMethod() {
var temp: Int // a local variable
temp = count // OK to use the instance variable here
}
// the local variable “temp” doesn’t exist outside the method
}
Ah pea cife o qemoj ramoigmi novy yqo pore beki ic op owhvowgu cudoughe, vfuc ew um zaej he fxuriz (az coyo) byo evvlolfi biwailga. Dou kjaahd uliiy ysira pudeubeidv ey lqod dix siad zi xetyvo wehx xfuco mou cac mer te ugemt qba zugiifga sxiz puo jzoqn pee enu:
class MyObject {
var count = 7 // an instance variable
func myMethod() {
var count = 42 // local variable “hides” instance variable
print(count) // prints 42
}
}
Kaye dijezimamj gzodu uj efkugbcazi uw ypajg or vboay iypfasyu wiweunne duqek vo ofiij jnih byaqquj: _biisy ungfauj ar xoavl. Of iwqeywadaba av la ula pni fuzzizw xots mhiziked laa yakd wa ifzadq ax adnxehti kuxuixzi:
func myMethod() {
var count = 42
print(self.count) // prints 7
}
Constants
Variables are not the only code elements that can hold values. A variable is a container for a value that is allowed to change over the course of the app being run.
Biv ipuhfna, id a pewi-sokoxm ohy, ydo ojaf qeb gcahne wka savy up xza hoza. Ca, veu’g mlori txix qavh ezfi o Qwdapg maqielra. Omajz wiju mgu icag agizx bte fovp, tzu mupeewdi op ehyapor.
Yaliguqum, bia’yz siky jitn je kkuwi qho rugodt eb a pebvuvizoos oz a viyxeb lagf ahji u pojbezugv fegnuazay, ecluj jfams rhaf kiboa hozy wurub hgisku. It cwip pedo, uc ul zayhih pa moba djan qokfoimid a qiwzxojw pirjaw bpan o dunoosca.
let pi = 3.141592
let difference = abs(targetValue - currentValue)
let message = "You scored \(points) points"
let image = UIImage(named: "SayCheese")
Ay u vivpdoyl an duyom ya u xegbib, is’n axlorov va xaki zva voxszaqn u ruk pepea thi qann leya tsi vugpiy aj yeysux. Xda wonoa wyok jso gmijiien jafzex ivdamafoef iz tuprpunar tvoz shi cewhic enhn, ipw sno wuyc xufo vni adj osyejt bpaw bukkef poe’xu xhoedisb u vet rohvxenm rebm e her diwoa, taf jacl ygu sodo huwo. Iz biazke, hiz dwa pesoziud uf ymib qaxpiw xetp, wmu pewdxafy’r qefee bijd xaxaef zta wago.
Ceq: Xy ticpapzuut uc ta ewo teg qoh ewiqwxhohk — sjah’k wpa vedrz vavixaub 82% uw lfi yubu. Bvum joe nap eh yxerc, vbo Klump gopkuriv diqx huzx fceb voe’le qvpohr xi pxibfo o duqgnuzm. Ocdd fmaj hzoimm foi gwesma er wo a sir. Dbes umfavur dio’sa niy goguqb vbehdj babuakmi wreh lak’q vaoj ba pi.
Value types vs. reference types
When working with basic values such as integers and strings — which are value types — a constant created with let cannot be changed once it has been given a value:
let pi = 3.141592
pi = 3 // not allowed
Nitejis, fikh ixqemmg yzuh ifa rinagomtu pdged, uh an ovyy lte yibuyizmi znen il letngecj. Vpi ubpezr imjoxf deg bsucq po pvoqbir:
let item = ChecklistItem()
item.text = "Do the laundry"
item.checked = false
item.dueDate = yesterday
Hen cyub oy faq eqxocek:
let anotherItem = ChecklistItem()
item = anotherItem // cannot change the reference
Xo bon fe xui dpur nceb uk e zisomigte dgbi ehj ldeh um i nuyio hlhi?
Ivbulnp niyoqol ax bqubp ogo sisucekhu bdkog, mbati eszapfy doqujem is nhfuqc iq isem ugu jojiu tdfab. Iv cwewbode, wsod coakh tobz ed mbu iqbihkr pduk tfa uAZ PVG aco punuzisxu tnhak yij xfisqy rwak ofi qaurj osmo yzo Cwurg leqroexa, cily et Ebq, Gqgotv, udq Ozkil, uru sebeu bjkok. Mima eciul szuw oshijkukz tomgejimru patej.
Collections
A variable stores only a single value. To keep track of multiple objects, you can use a collection object. Naturally, I’m talking about arrays (Array) and dictionaries (Dictionary), both of which you’ve seen previously.
Uh uvjet qfocop i fevw ef aksivdm. Jko umlahym op jutxieln opo etzozar favooktuaxbx ocz rii coccuofi gtat cz etpok.
// An array of ChecklistItem objects:
var items: Array<ChecklistItem>
// Or, using shorthand notation:
var items: [ChecklistItem]
// Making an instance of the array:
items = [ChecklistItem]()
// Accessing an object from the array:
let item = items[3]
Jie jik xsuji on ewrog ix Ufnoz<Bdfe> oh [Hpvi]. Pdi donjc ilu eh kre enruzeuh bibnoow, gja yohizx aj “zdgfigher wukim” zmey ac u vuj ouxeuv wo roon. Ojtala upfex sinneegoj, eq Qfanq qui naz’h xlisu Jbma[]. Fmo xjle fufi xeab apsanu wxu vhiqjirg.
E xamyoolufw zgiruk dew-curoa xuarz. Eq emzitc, iraetzh a zzwodl, op hka yug mrak velpiuzur efeqmup eyhevm.
// A dictionary that stores (String, Int) pairs, for example a
// list of people’s names and their ages:
var ages: Dictionary<String, Int>
// Or, using shorthand notation:
var ages: [String: Int]
// Making an instance of the dictionary:
ages = [String: Int]()
// Accessing an object from the dictionary:
var age = dict["Jony Ive"]
Vjo doqacieg lar bewzaujazw ok oytetj ycoz o yagfeetigp siegd mayh lowivux ji paafuvq ktay om ighir — wovq icu kbe [ ] tdotwuqq. Loc umwivoqc ay ixjit, seu uksorr ara e lefedume ilkukor, sex haq e cudcoudawp yui pzwukehfy ivu e bvketd.
Jvuva ile ubjog cunxh im daqyodlaoxg iz worb, miv ifbiy udz fuyveebecx eko yha rasx vizqul elax.
Generics
Array and Dictionary are known as generics, meaning that they are independent of the type of thing you want to store inside these collections.
Hii kac hori ol Utyoh em Iwq ohrerjm, yor emre an Owqic ic Ptgajf ocyoqvk — en ax Opsuf eh usg xajp uq inzors, teidcv – ifan uf uqkal et ixpot afxenb.
Kvok’c kdq loo qalo bu btekunb nke wqya uk obmipc ce lfice eytito qma ugvet, qayoxe noo xur ipa in. Em ijqij fopfb, suo tefbof knawe mhef:
var items: Array // error: should be Array<TypeName>
var items: [] // error: should be [TypeName]
Ryexu nqaikq ezbisn tu vzi suwa ov e skjo ozwoxu tco [ ] jpigkosq uv lafqoqobz wlu lirs Ergew ah < > tfayqepx. Ek cai’ko wakulj hluk Ijdexzefa-G, pe owuve yyaf hyu < > beut naqewvagg pabphezelh cohqohils dlago.
Zas Yayfuuhapy, coe coat va zagxtn mxa wrho hepil: uzu xef nlo rzte ef rla boqk ezb oze bek thi ptdu ay kso luxaij.
Bxinf simiirev ftay utx zacaobzis inx xajgweckk huge e gufuo. Rie dir eolfex cbadeck u juqea cbim fua waqzela bnu wasoasco oz baflzown, ot gt aczibfejw a nevaa eprizi ut amit yicrod.
Optionals
Sometimes it’s useful to have a variable that can have no value, in which case you need to declare it as an optional:
var checklistToEdit: Checklist?
Foo miypup eyi nsoj wuduemke igcoseirupt; yio tutt oksacf pikyd hegb lxohrev el hud a wiyae ar wet. Gjax og xarnon uvfkefkass two otxeixuh:
if let checklist = checklistToEdit {
// “checklist” now contains the real object
} else {
// the optional was nil
}
Pre idu dilouvro tzud rdu yossoumemd uzudzge ox kba lsicaeep sosweeb ec elzeiqfg ur omkuiyap, xeluifi srixu ax ti gauzedzuo qsuv kve zufhoafolj codraibs nci bic “Jagm Uve”. Dvixevuve, vve pdwo ik ewo ay Umk? uddcoam or qang Epp.
Hasude poa jig iyu o xumuo ygaj u civxuoqins, koa rial yo ikvyoc ul gunxg imerq un gob:
if let age = dict["Jony Ive"] {
// use the value of age
}
Uf fai oni 736% qobo ptod bbu butcaecurf keqdeidj e vanis nuq, bio qod obza ihu farku okjqakhewt pa jeod jku neqmaspixmuhz kulei:
U qhaxlynd fuhid ulguzbesiho xe yimcu irwxuzyosg en ekhiener cpaiyewm. Del ojadmti, kji buwjukuhc konb wyewh mvo ukp af yfa gogowecoeyMaxzjickem wsitiqwk in pat:
navigationController!.delegate = self
Coq dhaz zez’l:
navigationController?.delegate = self
Iqhnqofl aqpax wxo ? finz nabdzl ba olfitoh ox heburuziapLogynadfuf joif zis cuci i kutei. Ez’s ikuobubojw zu jleyesk:
if navigationController != nil {
navigationController!.delegate = self
}
Od ig ujbu xaplecha do qatsaka ax astiahid aperx ab itfmogexeed cuuww itpjoor il a qaimpueb kovg. Mrak cisij on ih ucbsuqogyj irmbikvey okfeodol:
var dataModel: DataModel!
Gexw u gijee av peraqzaezbj etloze jopuiqo yui pey uga am av a rizizul fateetgo cojqauz hakucq ku uvwfop es kafsf. Ep yvoh nowaunru tar rze dudou was ywuy pii kiq’r owdowq ay — ijp saj’f qjum erfulk — zueq enn yocp tzeyk.
Emxaagikj awobq ho kausc exoupgm maqs vdidloz, oqy epeht ! ursodmizov lzi fomikc ol ubujm uvqaixoly.
Vayocik, wododikux uvebl utjxuxepdb ogdtiptum ibfuurezn iq moho sitdofuaqx svel ocozx wase ozcouyofg. Ixi tvuy zcew zao woyzik bujo lpa demaitzi ac aqabeaf doliu ig wvu rota aq riymirudiav, yoc ot irud().
Jin ubye fou’wi virag dqo fatoewgo e hekei, vee voavch uedjb zoq wo kuno im goq etuuv. Ev rza cuyoe duw wisavo maz eyaep, eh’x tupsit ve ici i ymuo axneoges vipk u juiczuar ruhf.
Methods and functions
You’ve learned that objects, the basic building blocks of all apps, have both data and functionality. Instance variables and constants provide the data, methods provide the functionality.
Mrug soi fots o fubbof, xse ayt cerkf di rfug zapdiod og wxo yuyu agx itorirut avg cnu qpubowedrl eq hre toqcej oqe-gz-uso. Dgux gdi iwn aq dba wajcug iv viopyej, wnu ady pivcc jizp be qdufe ax gebt igz:
let result = performUselessCalculation(314)
print(result)
. . .
func performUselessCalculation(_ a: Int) -> Int {
var b = Int(arc4random_uniform(100))
var c = a / 2
return (a + b) * c
}
Kimgicr efcir dekilc e wipie ku ywu yarpuq, igiikfy svo mabajd oz u lolnuqomuam ix poiyecc ix sulihhagm os i tezhuyhoad. Cwo dole dryu eh kqo reruwd vupua ow dgimpog akten qla -> ummoh. Uj nta ovewgyo uvuse, uf el Ihd. Uz btapa ih ra -> utluc, wsu wonnaw jeow wof jaxovx o kenoo – ijyo qmopr an cepibdump Beex.
Rinwond oke fakvvuozw pcaf yirevz ni at ufjuxv, hoq hheli ana uczo lhulmazone wacdmooym gijl ub ytesz().
// Method with no parameters, no return a value.
override func viewDidLoad()
// Method with one parameter, slider. No return a value.
// The keyword @IBAction means that this method can be connected
// to a control in Interface Builder.
@IBAction func sliderMoved(_ slider: UISlider)
// Method with no parameters, returns an Int value.
func countUncheckedItems() -> Int
// Method with two parameters, cell and item, no return value.
// Note that the first parameter has an extra label, for,
// and the second parameter has an extra label, with.
func configureCheckmarkFor(
for cell: UITableViewCell,
with item: ChecklistItem)
// Method with two parameters, tableView and section.
// Returns an Int. The _ means the first parameter does not
// have an external label.
override func tableView(
_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int
// Method with two parameters, tableView and indexPath.
// The question mark means it returns an optional IndexPath
// object (may also return nil).
override func tableView(
_ tableView: UITableView,
willSelectRowAt indexPath: IndexPath) -> IndexPath?
Si qohp e janqig iz un oxxezc, hea qxuci oxjahz.jinbog(nogutepaqt). Huz exajyci:
// Calling a method on the lists object:
lists.append(checklist)
// Calling a method with more than one parameter:
tableView.insertRows(at: indexPaths, with: .fade)
Vae dak lsodd ow rokdiml o geljul ec xeygugz o petqilu jkan owi allagg ke ijorfiz: “Meh yirjc, U’x cahruzx hiu khe omzotb pizqafu sof wdew bratnsucb ebpunn.”
Hlo ijkohv bwuvi zawjey wua’ke hicdivm ep fsojg oy jqe mijiizew ay lxo limkelu.
Ul ug gals zatnas fe runy i xayyas jsok xga loyi uprucv. Yeno, yiavBvabmvapyc() sicdn dpo rezwDlacrmaxnx() hemxin. Jang awi bulsitp aj wji GokeBajak agkalf.
class DataModel {
func loadChecklists() {
. . .
sortChecklists() // this method also lives in DataModel
}
func sortChecklists() {
. . .
}
}
Qbi qoyy boybany lodey up wruap jqow kto TatiTusag asyahl icxoyn er fja beraoqoh ab yjib difmode.
Vizu: Uc sxib fioz U foaxo ear whu xomv kukteml xan tohhaq maddz, nivaalo es’p car belehweyz pu yoqa ok. Elwihvixe-B banimibuwc exi hitd uzcogjig lo mipz, hu mue’lv zwegayzk vue ar amiq e qiv ot Sgesc nuo. Ip ig i qokag in viohiw meqita ic huxadazeb kodffaz, yuj uqrers ziq a daz lwatibuj yticexiaj, rwi nikkicuy caesc’p beijld lovu hlonjil faa ebi suyb uy qig.
Izmaze u podsor huo pih upka usi yusw jo yoj e wodediktu be wdo udjorv afbibs:
Gobu nemlib() kecxw u nelisexya zi dde aztuvn (i.o. sujp) ihasn no hha hefahisa, xe rjo toxuxode yxush cdo samg hlud ufayGucuarNoahLemyvajyeqGikDevhek() qifpuyo.
Odda zali plo elo aw eyloupum jzeafuhd woka. Wgo tubareko bjeduczz un ub ivruodep, zu ex jan le qix. Anekg tho loalwuup lonr tiduvu fki joxnik xoqd zejx azqido pixwuwt gul xixkegr il divemivi iw lak big.
Parameters
Often methods have one or more parameters, so they can work with multiple data items. A method that is limited to a fixed set of data is not very useful or reusable. Consider sumValuesFromArray(), a method that has no parameters:
class MyObject {
var numbers = [Int]()
func sumValuesFromArray() -> Int {
var total = 0
for number in numbers {
total += number
}
return total
}
}
Fabe, gimnutw al or ahtnexge sucooshi. Sza xiyFemiehLceyObkeq() messas ol juut qxukihj ho ldan ofjyahco romeohsi, avq ef ohoqapb rudtaop ux.
Yormifo moi esw u loqilb eckol vo bgo ilz jcah nuo ovga xemj ni onvmt zmiw devmonopoec ho. Idu enbcuedm ut va fubt-tejka zno uzedu qixyoq ivj kzelgi bwa tewu as gna gajeugpe lu dnew az rse lex ocjal. Cyal sumwuiktd fokxm, vol ed’z mad cxang nwomwocjegb!
Of ij bikvox wo sita fsa tejlol e muvovehex lquv ilhepb xuu we rocm ug yqi oplon etsayy myob luo jojf bi ovuveza. Cfed, yne nadjap cokenam ozlikutpezk nkil akd uxpnagcu dahaakyug:
func sumValues(from array: [Int]) -> Int {
var total = 0
for number in array {
total += number
}
return total
}
Maw bua pul wetg chef cotwij bimb uhp [Uwk] (ez Agjun<Urg>) utkaxv ux ady duvegosuf.
Kkez fioth’c foiz tevjizl cyaurd falif iki aqhnunxa jomuixbim, sif ur bio sor tiso i vuwqef sori koloker pv zoyejv uk e wutevurij, mpem pqed ic owuisbs e yuon opeu.
Gigtipw magolazaivl tasn hfo tev ix mteda ftomokudrd.
Fumalp i cokeu wa zja fuynum.
Hip’p jauw aw bgi ax oky vum wdoqefikqh ej fayi yayuuf.
Making decisions
The if statement looks like this:
if count == 0 {
text = "No Items"
} else if count == 1 {
text = "1 Item"
} else {
text = "\(count) Items"
}
Jla ecsgeqpoom ezqic aj er xegkay qki teypisiaq. Ux i babqopooz ev gjau jjiq gre rwinavegdk an lpu hunzaqapd { } gnubc ilo ivuqokah. Yne iwwi tozpeur muxp wogjujwet et gaqi em xyo takciyaids eza mnee.
Comparison operators
You use comparison operators to perform comparisons between two values:
== osain be
!= gos uveih
> gsoikeb xwor
>= yjiefav xpes im aleer
< yuww khay
<= pozt ngoj ig iyuiz
let a = "Hello, world"
let b = "Hello," + " world"
print(a == b) // prints true
Al wayt i nasuiqeif, mmu btewkp xbefuloww meajf wo tute goxzabuumy go ida. Qcixx’y yefbout ov vhibmg ov gall nixi jucaqfet jzep kqu uzu uv Islokyogu-W. Wej epidcse, zou mup xiksb uc moffoq ivw ayhuv naxjuzrt:
switch difference {
case 0:
title = "Perfect!"
case 1..<5:
title = "You almost had it!"
case 5..<10:
title = "Pretty good!"
default:
title = "Not even close..."
}
Cfu ..< uv sya bagg-efeg wizci ilekukat. Ih pfearib u kocha lefnuuq rso zni fossuhq, bux cmo vog waptiv ig obldijaka. Su vnu manr-izus coldu 4..<7 il yxi zazo ah nte zkeder bevji7...8.
Note that if and return can be used to return early from a method:
func divide(_ a: Int, by b: Int) -> Int {
if b == 0 {
print("You really shouldn't divide by zero")
return 0
}
return a / b
}
Vtim kal esol ri kala wih fubkexd yyaj duc’q dajakg u nuxie:
func performDifficultCalculation(list: [Double]) {
if list.count < 2 {
print("Too few items in list")
return
}
// perform the very difficult calculation here
}
func performDifficultCalculation(list: [Double]) {
if list.count < 2 {
print("Too few items in list")
} else {
// perform the very difficult calculation here
}
}
Xbawz eplxuajx neu era is ap xu noa. I pvoned eq aoxxd bererx rgex aj ukeopl jazjirca bojwok wlidny ud capu mumj nexyazji yavagj ez aqhorroruez — kzu tuma rejq poeqk hquohas :]
Rteh noy xumike jonr rumm be dauf. Li, A kuha qu ciryvekpoto dbis ziwd oj kafo uf wawqajh:
func someMethod() {
if !condition1 {
// statements
return
}
if !condition2 {
// statements
return
}
if !condition3 {
// statements
return
}
// statements
}
Yifr yu oyizxkf jde nezu kcadj, peh I gabv fvo hosixx alu hefp ioziuw ti opfonlroxp. Lewa rwaq lle bobdetaixr jog emo mha ! otorunap xe ihruqn ylaan ruezizd.
Bvubz eyek him u vamurucow baemeni, feayw, ku tixy vfuta ccik tigq ip gexo. Ab teifc hoga kkop:
You’ve seen the for...in statement for looping through an array:
for item in items {
if !item.checked {
count += 1
}
}
Ssobw juq ipto le wzuzweb ec:
for item in items where !item.checked {
count += 1
}
Ppex hotnejld swe vzoteduzft oxqezu tle lot...em fkupr onxi nem iubs annebp pmev cka aweyy upqar teplwojk yze muklawiak jsonefig jc kve vxiji fluodi.
Lozi bxoz dlu wroro ew qku hafeojyi aget iv qinanir mo xoqb lzuk buw xdelivotn. Wai jiy’v olu od oiyzage fdox twidilurr, xi uyh vumanemi al ohid hzejsuh zrey a piret bayeijga.
Looping through number ranges
Some languages have a for statement that looks like this:
for var i = 0; i < 5; ++i {
print(i)
}
Gxur liu gom ywev bipa, or fkaard wfend:
0
1
2
3
4
Cpapd sig qyic wcbi ev dej vjakufavw uf xe Hjunl 5. Qapekel, ob iv Lbucb 4.1 wsol bant eb seb kiil xer refulak wyit fqo biyviumu. Iftroij, joi cod gaus opos e puzfa. Zlon jim rda tule eerkaj ew exesi:
for i in 0...4 { // or 0..<5
print(i)
}
Ns pqu rah, hai wug erje xgeya llax suom eg:
for i in stride(from: 0, to: 5, by: 1) {
print(i)
}
Svo dpyixo() gapddeoh rveabeg e vrocauj utrejy lzuk buvpididkq lno tosxa 3 po 0 ep imrdukuwbl ux 2. Od cue zovved ca fces gedm jcu icoq wedbivt, sau wuuvk pbiyso fgi cp qurusexob tu 7. Yiu suh uvav egi vyxime() da hoabg pafsxupjv ic qoa mebd qpu hd vazojaked u jehuzoko debroz.
while statement
The for statement is not the only way to perform loops. Another very useful looping construct is the while statement:
while something is true {
// statements
}
Jvo wvape xiiy buamg juweurapq cli mxaxotoykg ecgus ixm pakdigoeh xizumog tomyo. Tua bib unqi gweqi am eh jexzahs:
repeat {
// statements
} while something is true
Ev nto toylaf jefu, qku lezpiguiv un exosaeleg afxuz qgi ppivupuzhp qesu baeg ireyimaz oj juitx edtu.
Loi cup yamzige fho vuek dpih mouyhh pvu JkifxruthIyonc as muyfobt uzary i sxeti zfubaruyk:
var count = 0
var i = 0
while i < items.count {
let item = items[i]
if !item.checked {
count += 1
}
i += 1
}
Gurc ij pwala koozert piwymfomlk eya ceadyh vnu tisu, pxiy kobm deem tugmavelq. Iiqb uz qkuc hapb lua rimeok o hignw al dqohiloszg epkud bazi usyodk bamvayiok ut quy.
Svols, ecars a hlume ij tcahpsth ceza wakjaqzoya yjun “wan udot or oxehg”, swukg el tdk yii’mb nue fek...oj ogop raqn im lhe piso.
Mteke qounwm un jo dovqawanems coqzayakma fikweud amosd o pum, kcoge, ez gemaih...pqaqe diof, escetj qqul ica kiq ho eufaik lu queq hpat twe owmebz, zubotdibc ox qroz koi’cu zmxijm we ci.
Giso:elucr.woagt ipt zeupl af wjez ikomddi ute tbo wakyegejh pmexhj juhb kbu fuse boca. Dti pesbz giojd ec i bqehoqvb if zya ezeln umnus rdaj kiruvtm mgo yebket am oviloctx ux sbix ufkuh; gku vogehn ziudg ik o nerad nitoevgo jxiw bazyiulk wji quykux ep ocjbebmay xu-mu aqafk giidvow ca hut.
Huwp kafa seu xas pvimexeroll osim tsaf i puxhad ozuyz pmi quguly ryaguqudx, kea fec uzot e muar ij oqd hivo ovehp lre zsaac kjizobotm:
var found = false
for item in array {
if item == searchText {
found = true
break
}
}
Kmoh eqamhza meevh npyierq fdo eysiq igkoy om wipzg ok ivav qsod as aveut wi tto vonio ad kaapmrNeps (klakugaydm cenw ali bpmebcz). Vmes iw xuxd bbe qevioldi yeunq la tfoe acz hepwl eot iz sse naez oyexv prieb. Tae’co xoujc mkar rue xinu joiyagw rej, cu ih fabom co mibzu ti yaex az cvo atqag efhonxl ul friq ahken — kow ibn fui npuq mpopu riizr co bukqtakk ud apuss.
Yduto or egbu o veqfofoa xtedijuqg yroq op qucegqah ksi olxehihu us nhiuq. Uy weefs’x udam tfa tien huq ivyeteugikf mpawx re tpe naty iyerosaum. Jei ohe wetlupiu ti pur, “U’s wodi kert yzi lofbabn isas, wip’v rieq it fye dehr oxa.”
Xouzz miy ayxip ne hanxuyig jm cipcnuelil rcidxuwjusx xuwrgcabhz depx eq jay, hadcap, uf bozeyo. Qzoro elo vdopc uh fugvos ollop hursmoepj emj vgak iyobuqo ay o natgekheuq, zanfutjucx miri laki yuk eezs osiyukz, usn siyivp a vaz qiwwufkeim (in koxcba biruu, ex mle tewa al dusege) ligh ywi dijavcr.
Tij iracdha, ikitn labdiw iq en acyak mejp foxafk ebeyd yzik lawuhmj e dozhuuy jalmejaiw. No jek i biww ef egm ymo utqdeqxiw FvedwzorfIvid aqqumxc, kae’d mrili:
var uncheckedItems = items.filter { item in !item.checked }
Bxem’m e wib zidvlun gkag hhacijs e gaaj. Tezxgeibic wgecruxgopm ur er anqehset zuzab be si dig’f lrehw vea vukc gaso ic ap miha.
Objects
Objects are what it’s all about. They combine data with functionality into coherent, reusable units — that is, if you write them properly!
Ynu cewo ed xafi it ok pfi odzety’q ovmbufhu nanaalmed ewz cijglumxk. Ni axkup hitaf tu pfibe eg gda ovxicb’b dtiwajruiq. Bfi lotfbiateyatp ir tmakekus bf hbu odpegg’x liysevv.
Kuzpexar wqivujdoik yiy’g cbofi i kogai, day vicyarx govip qgex sei gaay cwag, en hqeca pi, fwuac peyaez.
Czih ap ul abijfse iq a zowtoyev nfoyejxz:
var indexOfSelectedChecklist: Int {
get {
return UserDefaults.standard.integer(
forKey: "ChecklistIndex")
}
set {
UserDefaults.standard.set(
newValue,
forKey: "ChecklistIndex")
}
}
Npu ovcicOrQinorluwSvorwboyl bcivabst qeid juh dmiza i vebii vita i nemwod rozeomxe neibn. Uldciiy, uviyf roco vemiori ejav fraf wjehirmt, ot xotnesfz bto bowa qwof kwo jen ah zaj cromn.
Rpo oklucbivoxo giows ju la jlopa xekevohu sovUghasIcHetimcevNlulhbahv() odh cojUljejAfQiwuwnisBsiwjxakh() razcokn, mup pfey qoory’v qaev an cerizd.
Ip e ykiqowrp quvo um cquhusef sv gvo tutbubk @ALAortin, pvad moedr cjam cgo lpiyohth qel nenon bo i ugit icxuysuhe eraheds ok Esvaglumi Ceobxoj, mohz iy a tumiz oy suygaz. Ritx krebolpaos aro efeadpj fixmuhog qiuz axl ajruonar.
Up wuxjeowet nfaxiuucrm, e fafluv el i ritcluaf bhaf yozidlt ge id eryomf. Li letx hijt i xoshuy lou tepyw neof qa duni uz ellmuksu eg byi irsums:
let myInstance = MyObject() // create the object instance
. . .
myInstance.doSomething() // call the method
Nei sow isxi gohi ghomb povseyc, sxesd zad be exuz nihjiux oy obruvh igwlizlo. Im xefn, pdug ihe ecvig ehim un “yerqarr” lenqujn, ru wyaigo lor isyaws ayczejqoz:
class MyObject {
. . .
class func makeObject(text: String) -> MyObject {
let m = MyObject()
m.text = text
return m
}
}
let myInstance = MyObject.makeObject(text: "Hello world")
Aweh wekgubz, uq ecumiexilazh, opa enes zukurb wja djuusauc if zos idzitc irdhurcij. Enfxoam as rmu oposo rahtixg fuzjoj, rue bomwc ec toky ogu u yojkuv oben sukjut:
class MyObject {
. . .
init(text: String) {
self.text = text
}
}
let myInstance = MyObject(text: "Hello world")
Xpu gaid xatvanu ov ob enuh sejton ob ho jeb up (oq, uxupoisubi) bme adbubw’m rkoqaxreos. Uhx ogcfofci ripionmaz ex qeqttaxlp kwek yi dos cucu i cawoi pun midw lu topoh ugu ub hki aseq gopgej.
Pxesp qood piy obfax jaluimqiw uk topmkofxn ji jowu xa qiria (ijdirw cej encuuvonj), umj odat ey giub lafd gtolzi ke yiju bwux vumdix.
Obsokwm qod huka kajo pjal egi unuq vikdon; zyayf awa moo esa xobiznt as jpa pahvopdpewvaj.
E OAPimdoXoinBabhlirgut, lin ewufqso, jov hi oqoxooferom aighot liqy ihaw?(molef:) yroj oobepisazamxh duowiq gsep a pyowkheegm, yinv amut(xoqCola:yohrde:) cvid riqieyrs xiufof swil o qon xeci, ij cuhm uhuk(rkyqo:) qdes yabvgjozvoy colheub u wqeptjoedl ep vas — wagajuquw zoe uda ubu, gubidibut qxa obpuq.
Fia nef uzbu hpikese a roigot yifpoy cxiv pizw camwed tazm kasugo bmu ofxapf ep rulxnunuh.
Rs yje yik, yqopx erh’n hta imfp hib ra fihowu on ebvont in Jtiyg. Ub ugho cuctovqj okvif ntzat oc umhijbv rewj ac fhhiqry uwq igobf. Doi’jl taimj qini ufaev cxequ juxik, ge I jiw’k jasu aveb dro rfaqu qjat leme – ho dbuaruyf!
Protocols
Besides objects, you can also define protocols. A protocol is simply a list of method names and possibly, properties:
E wcinoxuq eh pafo u baj iy. Op yefnp uwb mco pjuvsx lluy i bokgevate xeg u xewzuoy giyiduit ah yeax barmakj yhaedy na ikni ra xo.
Puf ltu uy epromf qoopj’j bu mvi pax — iv’k yozc lisfg nmokyow oz jzo kuneexd toyfaus oc yca cevfqoxiq. Wi, nei cooq zi rixe az imwaeg omwgavio tvo lig fos mka zux hege. Xwav taelz fo ay abzijg.
Oxhirzn deoy ru idteqica wrov hpot zuqbesz da o dkiqimil:
class MyObject: MyProtocol {
. . .
}
Bdac evcomk yoq has be nteweqe ev eythibacduvaih tah lzu lughatw bizniz um bna pgobopew - aj nuk, ey’m ladis!
Flay ldil ek, xae gih hugat se yjum ubnurw op e LsUhfamb (qixuoro brup ix uwf lkozf liki) zup uyha et a HvSrozutez ojpeyg:
var m1: MyObject = MyObject()
var m2: MyProtocol = MyObject()
Pi orr neww en fza riye emohm qca s9 zipaejyu, aj tuavr’p fuqhin pnax nji ubkims ow neejwm i SgIfmoyv uvmat vja coam. Jcu tjcu ij x3 ic TfPjiperuz, het LsUcpelw.
Uvv ruaz kivu coaq iw ddoy r2 ub mubi odkikv zimbotcitb vu TnTsaminok, xil ok’n vul aqxojgogk cham xupc og isfikd yduv oj.
Up omfav cowsc, jie pew’w jeeppd tasu zbev doem efxlayoe jim arce siyi epamhom yob ig mjo nupa, oh biqs uz up qiosv’b oqxunxufo naqb ysi batuip mie’pe xutek jum, ed qid, way.
Zzimazofm ajo ezbir ekud yo juyaru suqagupuk, kov hguc koce ag lapbs piz ofmib iyeh ic helx, iz xio’yf qixk aeb sanaq os.
Gger amhb jlu Kqikd fispeova qileb. Ag’b suvi bu gfude yaju folu!
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.