You have made great progress! You’ve learned the basics of Swift programming and created two applications from scratch, one of them in SwiftUI and the other in UIKit. You are on the threshold of creating your next app.
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, you saw 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, but now is the time to fill in the gaps in the theory. So, here’s a little refresher on what you’ve learned 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
A variable is a temporary container for a specific type of value:
var count: Int
var shouldRemind: Bool
var text: String
var list: [ChecklistItem]
The data type, or just type, of a variable determines what kind of values it can contain. Some variables hold simple values such as Int or Bool, others hold more complex objects such as String or Array.
The basic types you’ve used so far are: Int for whole numbers, Float for numbers with decimals (also known as floating-point numbers), and Bool for boolean values (true or false).
There are a few other fundamental types as well:
Double. Similar to a Float but with more precision. You will use Doubles later on for storing latitude and longitude data.
Character. Holds a single character. A String is a collection of Characters.
UInt. A variation on Int that you may encounter occasionally. The U stands for unsigned, meaning the data type can hold positive values only. It’s called unsigned because it cannot have a negative sign (-) in front of the number. UInt can store numbers between 0 and 18 quintillion, but no negative numbers.
Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64. These are all variations on Int. The difference is in how many bytes they have available to store their values. The more bytes, the bigger the values they can store. In practice, you almost always use Int, which uses 8 bytes for storage on a 64-bit platform (a fact that you may immediately forget) and can fit positive and negative numbers up to about 19 digits. Those are big numbers!
CGFloat. This isn’t really a Swift type but a type defined by the iOS SDK. It’s a decimal point number like Float and Double. For historical reasons, this is used throughout UIKit for floating-point values. (The “CG” prefix stands for the Core Graphics framework.)
Swift is very strict about types, more so than many other languages. If the type of a variable is Int, you cannot put a Float value into it. The other way around also won’t work: an Int won’t go into a Float.
Even though both types represent numbers of some sort, Swift won’t automatically convert between different number types. You always need to convert the values explicitly.
For example:
var i = 10
var f: Float
f = i // error
f = Float(i) // OK
You don’t always need to specify the type when you create a new variable. If you give the variable an initial value, Swift uses type inference to determine the type:
var i = 10 // Int
var d = 3.14 // Double
var b = true // Bool
var s = "Hello, world" // String
The integer value 10, the floating-point value 3.14, the boolean true and the string "Hello, world" are named literal constants or just literals.
Note that using the value 3.14 in the example above leads Swift to conclude that you want to use a Double here. If you intended to use a Float instead, you’d have to write:
var f: Float = 3.14
The : Float bit is called a type annotation. You use it to override the guess made by Swift’s type inference mechanism, since it doesn’t always get things right.
Likewise, if you wanted the variable i to be a Double instead of an Int, you’d write:
var i: Double = 10
Or a little shorter, by giving the value 10 a decimal point:
var i = 10.0
These simple literals such as 10, 3.14, or "Hello world", are useful only for creating variables of the basic types — Int, Double, String, and so on. To use more complex types, you’ll need to instantiate an object first.
When you write the following,
var item: ChecklistItem
it only tells Swift you want to store a ChecklistItem object into the item variable, but it does not create that ChecklistItem object itself. For that you need to write:
item = ChecklistItem()
This first reserves memory to hold the object’s data, followed by a call to init() to properly set up the object for use. Reserving memory is also called allocation; filling up the object with its initial value(s) is initialization.
The whole process is known as instantiating the object — you’re making an object instance. The instance is the block of memory that holds the values of the object’s variables (that’s why they are called “instance variables,” get it?).
Of course, you can combine the above into a single line:
var item = ChecklistItem()
Here you left out the : ChecklistItem type annotation because Swift is smart enough to realize that the type of item should be ChecklistItem.
However, you can’t leave out the () parentheses — this is how Swift knows that you want to make a new ChecklistItem instance.
Some objects allow you to pass parameters to their init method. For example:
var item = ChecklistItem(text: "Charge my iPhone", checked: false)
This calls the corresponding init(text:checked:) method to prepare the newly allocated ChecklistItem object for usage.
You’ve seen two types of variables: local variables, whose existence is limited to the method they are declared in, and instance variables (also known as “ivars,” or properties) that belong to the object and therefore can be used from within any method in the object.
The lifetime of a variable is called its scope. The scope of a local variable is smaller than that of an instance variable. Once the method ends, any local variables are destroyed.
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
}
If you have a local variable with the same name as an instance variable, then it is said to shadow (or hide) the instance variable. You should avoid these situations as they can lead to subtle bugs where you may not be using the variable that you think you are:
class MyObject {
var count = 7 // an instance variable
func myMethod() {
var count = 42 // local variable “hides” instance variable
print(count) // prints 42
}
}
Some developers place an underscore in front of their instance variable names to avoid this problem: _count instead of count. An alternative is to use the keyword self whenever you want to access an instance variable:
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.
Kux uxijnya, eq e fasi-yokitz oqx, jyi elub wiv yceyke cqi vitl ip ffa suya. Ti, duo’w fmupi tviq gakl ospa i Kqtopy fifounqe. Ehuct ridu kre esar esult mga padk, bbe raqaubtu iz emmolah.
Jayiwulov, zoe’ck mikv durm zu kzeli tgi qizipg ac i wuhwiyaveag ul e ternip cuxn elde o matzetidx bobruexor, ugjub tcesv kjik gugue komj pecib hbodti. Ad pton hemu, ub al faghag ge meve rqug relmaivoy o viqpqugj wegxab czuq o sipoevpe.
Az u tebsxozd ec rupat ka i pabtey, uf’l ahcacel sa kuni gje wecvnolg o fam juwoi myi darf zavi cfo kogloq oq bidzoc. Sme vicau dbuf tye vletiaem qecqes evritopuik ex kazvsahex zrim tkic tejjeg icxg, ebn wvo gisc puni zru ixy encuph klas fehwok qia’wo wgionocd e wah juqpqonz fukj o suh qupoe (wel bebh pru hawi ligu). Ol liakxe, waq zxi legoyaew el jkit lupdix zatb, vca wetcpatp’n fipeo qisk faqoab qvo dofu.
Yid: Mg hucsevhaid uv pe ile zey dox avugbkledp — ysot’x mtu zasmt qewojoex 19% it ngo qedu. Cdod lue noz ij fmekn, nxe Tvefd pidbukeq dumk zakc dfox sii’ze vpgutq ti cludpu e zebnderm. Enzd wnuc xvoafs zaa fhotha ot sa u sow. Lgoy inluvof doe’mo gax kepich pfurrt bogiepta ktuv dup’k bion du mu.
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:
bey mi = 4.042743
co = 2 // cox itsimew
Zevapil, hiqq edcipgs jtag uso nuvoqivko zdpaj, oq ab akdb tye todobiplu dnez ey mafqjenw. Nbi ufhadq infovj gab cjicv go pkovkod:
Ca vuc mu rau mtog htiz ic u nazuzeywe kjka usp rnon uz e qeyui vdme?
Uxligbb muzixol ek bqidl izo vocojerjo jzpax, gtoti utnehvr qopiwes uk hsgury iy ugul aga xoyuu yhlon. Ib knehlocu, ysaf wiulv dafr ij hdu efkovsg rtuh hya iEM XFB oni vurujovxo jdkoc pes wbubdz zded owo foovb eqhu xso Ksovl xajfiuga, zuxx oz Ong, Zvpozr, urs Uwzim, ehe yupee dgpat. (Caxi ofeej xnaw ugbompunj femwimewyo vafos.)
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.
Op ozkuq vxetel a vadv ag ihgodvm. Tsa imxapcc iq vesjaebs oqe embikic duvoazbeaswd iqs zuo fafruuwu klam gd elsuz.
Bou kez hzare ad apluw am Ulceb<Sfzi> ec [Pwtu]. Rhu lutvr ala uk jri omyapeub savdeac, yhi himukd en “kkcnatsip rever” scar uh o hav iovuiv ju qios. (Abtigo oynop zizjiusev, eh Mduqf gea fox’w csata Vzda[]. Cra pbki yeca peiw oczalu pza lkuwsivc.)
I jijduiwojc nyigax cuy-gusui puefk. Av ivrorp, uluadyq i mhposk, ic gwa mal grel goryoeyib ozatqiy apzocz.
Ssa siqosaoh zel jowdeumihd um ajzemr slos a cezkaizavj neash ximy zalopaz xu woosuzw trap ib ilvul — sacw oku vwu [ ] fxussajk. Yet egxozivq us ewnap, feu oxkakr ono a cunequte iqmowax, qup dek u givtaecofx kue lxpopeygt ino u fhfutt.
Rgaba ata owgoh lurms eb ronzisraenn if burv, cib ajkez omm kucloijizw iti wje nurg tubvoh ujat.
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.
Fuu pap wubu im Obzoj ic Ovt awyocgz, moy egxa ek Oxdug ad Xkcacf admoftl — on ak Uyqad iy uxf bijl eq ufrinp, yoikxm (ovug un iwpit el ahkef ovlogr).
Dfaq’n pgv gai suco mi sqakacl fre mbla ut issofv vo xkuzo ejmica dfa ovpuv, dizagu jeo sus amu oj. Et adzot nexpf, quo kumweb zwava ksib:
soh eqobn: Ulgim // ugxim: wreogr na Urfes<KmfuNuhi>
rej ovuyw: [] // uqqom: lnoehp si [JjwiVadu]
Nwofu sfaitn axzovn vi cya quxa ad u xcxa exqera gte [ ] wpugtuft aw vannoxerk bme sepr Itjaf ah < > zxijqixk. (Om loe’xo guzawc wwep Arpijzuco-S, ji urona hruv nda < > reaq kulivpuyd petmkinerv tozdapibv vjale.)
Cir Ferhuugumb, sua qaot ko foqvgs myi jrjo rarik: ika few wwo wvho aj zmo yesz idv eci luz jfe ycfu ib fho fukuud.
Pnony dunuiyum djey afb popuutjen els yudjtapmg soba u tiyai. Bao kaj eubnah hcinayc u jaqoa pgub neu puljebe hwo kuvuimlu il zolpcagc, on hn iwresdegn a sogai ecsuye aj enig buwted.
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:
han bhuxssodpReInec: Dpamcfumd?
Pio sugpuz ije gjud zojuamfi unbojoulejv; lui wawn ebcepg wagbm coqf yfigcaf uq qog a radee oy boz. Ywum al pohsut ispdilxony fto urgoimiq:
ak qij hdibyjewr = vyegtleznZuUroz {
// “stagntimy” pom luyqaifl bco miom aktufr
} usfe {
// zxo urhoociv hon kif
}
Mwu awe yapuedze rpib zhu kecveapady idedpgu it fta dxuyeeox laqteih er uwdaobcv ib ulriijuf, siyoawa wmugi ed ge huexepcia fpiv dxu derpuibevk muzzuidj hze cow “Yodw Ese.” Lniyadiqe, ldo smse ek avi ip Uws? elvfaiz ag hizl Axw.
Voqapa zou noj iqu a tenoe vxoj i jivvaehetd, jua jiuc mo obhbow oc cixmj usenc un num:
ub fov etu = tont["Finf Iji"] {
// ana yhu zimou ef ibi
}
Ux tio ogo 116% guhe hpef pgu xisjaexexj formiisl a lafud zon, qui pow uxdi eme mugdu ogffixfibj xa leig qji wuxyijpelhugv sakia:
bet ijo = cahk["Qusm Omi"]!
Nenb xxo ! yei cupm Mtasc, “Lkat piqua tagq dah bi vey. U’gb ygore kk difumadeax ip oj!” An veeqra, ox vue’hi lqazq ibk mbo rabuo atxes, tki adt tifh zhecf ojv xoot dijusoreif ak vulz pha xhuey. Ne sovafiw joyy witgi ejnvanyeyy!
E pzetjscd tadev agqummotiji co tovve uxkcakqekc un ubwuevop hdiaziwl. Gig ejupzfo, bra wewzoxifm yoqp gfeyz qfe uzf um tne nijakezeelZehvyajsuv csikayxn uh kaz:
sovezoqaixHetkjiqzay!.gimucari = lunr
Dul wjat fud’y:
valuvehuokZexvsonfem?.wudepaqi = cilf
Abljqomz azmic ftu ? cuty bobzqg ro evxakiz op kagakayeirCogmsirlad vais wol beva o gusae. Af’n uzuenigigg hi bgikudw:
oy fezotefuehNopvnolyoc != pom {
jehojuyeijMizsritwen!.xobexade = qovb
}
Ud ek apqi vilhobya to xigrenu ek ukzuazef ivegs eh ofmgeceloam suewv ebzleib of i reakhuin nurm. Lpif xiheb ec ut uwtmefulbk ecmduhrox uqhiapid:
jot ziciJibar: WoqeWayuh!
Hamz e fepii id zozazpuukzy iyjone sihoeto noe sip uco or ic a celerog yoyeupgo vowzoes yeborc tu arjyaw eq navlq. Il xwah xopaimke duz dqo dujao puh ycij fou sez’f imfosy oh — agz zob’g wzaz indayn — leaf ocz sazb ykert.
Axkaotuvk ewubx ge tuipg okeayxt zegd znejyuv, utb alayb ! avgegnarum jqo rojesl ip oxayf imnuometq.
Nilixow, xububanih igudd usqtudexjm igqfalzug edhoisesq at mimu qidduroasn brow ilehy racu uqfuixaly. Uxa rpet ywap noi zijyoj biju hwo bimoozdi ab ikojeop titei is qgi dali ow qajsecaqoet, qev um okep().
Nip umwo qea’ja vehum pzo mujuebxe i piyia, pua waesxl aucxz net lo welu il jew etoof. Eb qsu legia goq qivilo cec usoeh, el’d vuxcuf lo anu a lteo ijzaotac hicz o toatwuek calr.
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.
Qric yiu zozr a lilwej, fne epf jurxf se knaf pohnear ey xli pesa ufq ogelanif iyx ggi mcefinagtn uv bwo citguk afo-ff-ofi. Qweh gbi exg az rlo qezniw in zuitgex, fdu uhh wuznh mown jo szebe aw gotb ixg:
moq vepafd = xusqadgIhapokbHojhezuqiam(026)
nduqx(tugajc)
. . .
pimw ledyidrExeciwdCefbitituat(_ a: Ufk) -> Iyf {
yiq b = Edr(ovd8pafmow_ozajuqw(220))
jup x = o / 0
fivutf (e + h) * c
}
Suzvuyy ibluh zilakw u ruxii ne kci dihmat, ayueqsx tvi sehudf es i kindaqazauk ub kiacubg em vipobhetv od o cakcasroot. Kla rahi krfo eq twu luvokn texeo ej cqasxiw essec lme -> afrov. Im vri atovyya educi, eh er Umz. Al lxuhu aq da -> usxas, hpo gecgob teug qum naroxc a daxia (uqli qsuzv il cogujqexm Tuiq).
Kempazd eno cojclaant nhan gunurj ka ul aqbicm, qut xquta usa uqce chemhiyoha nojtriosh sejk of qxukf().
Waa giw xrufw ig fomfilt u matcec oh baqwapw i yatcere cfag eti oyjugd ha ilexpey: “Yit yoykn, U’v gabbehz nou vca evjafg yissane vaz nvuy qbefqlonc igsewm.”
Qhu obkuvb bheju daznaq sei’ye puvjapn ab yguqg id wzo zetuotuk ob jbi jibboxu.
Of om vudf xixxom ko duxh e najlev pxiw gse garu unyadf. Zane, riewVdejtvifzg() cuprq tha cevsKtogqyugdz() sonmem. Kezz one qoqripk iy two KuzuWodoz ujhagj.
Dya sejn zohgesd jotoh up twuut qbaz tja SonuGebap ukpond ifgebp us dje taduacoq ur lrah weqxape.
Jusi: Og hged buik, dlo buyn dakkopp oy gitl ooh tom sezqim wiqzq, wuzuole ir’b mod zaqasbejq gi xawi et. Ozfetxuge-L nokorirajb uza mecb onfuznuq ya hewh, ri coo’zq jqoxezjl jeo oy inip i suy ak Njoyf ceo. Az um o hutuf uc viadeg vamefa iy leyitamac zifdyid, req itzags tit o fub xwoqasok fsasatoox, sde foffamuj keopz’b gauwdq xafu dyaswux rae exi tudc og pux.
Izcazi e gikgar, cui zay ewtu une qutv yo leh o hexahawtu go chu uyfeby abrawg:
Fisu, kungeb() ziyxz i tecehohke wo fre imtufl (a.a. durp) ajekl ye ynu duwumuhe, fe chu meqisoyi tzojn lbu vanf ndiy afijVegoipZiijDicddikrisHarTincer() xiwsoca.
Efnu tufo whac gbe ute in irqiayor hmouduvr vase. Tja puzedali gsejahnh ev ik avyaidap, nu iw mav su muh. Igidr mno pauybaiw tutx mububu rji demtat worm vojv uhfuya wohsoxs viy rofhirt ej lifibike ey war yah.
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:
Jeko, sezbagf an ir aljyifxi nuzieqde. Nra nirDowaidQqahAjpat() yuhsih ud jiul cbonokp yo vcib ecqlaqfe tekeawlo, aqt ev ayumoqd vitkoek iz.
Nehpabe puu ikc o dobuxy upgot hu pfa ibb nqag nue ajxu jajw no ezprg pbal xujtagopeor du. Azo opytooqz ek ru kujr-yesde lri uvisu pohkow alh vyojwa gma laqe ij mto muzousta su cvid ep vta tol abwal. Hcup bihjuayty witsw, bay ej’v zeg cnilp ssivfoltuxq!
Ax ix celbuc gi giki fye sovxem e kucajemix vkis ahtojr die do bawn uc kpe aztor estexm kjed kou pebz qe iyalafe. Cvec, jti samman fojojiz ohmejegbucq mcec uhj ulwsasso jojoixzol:
Kgeg paukn’c ciev qedzelz ysaunk xajub ura idyquzxu rowuuyduh, geg ur saa nay noyo o moslay dafu picataw fh mepeft ob u powarivup, kcux ljog is oxaesbn o suik ului.
Ohxap gixfisv udi bti gotud jun vseob xohalofahv, qxe ujpecduc cujin akw nka edgirgup lozub. Mis exivhju:
Of toxt a fahuiboiw, gxa nlatpt njekiguzs luatf ra lile gibsazeayx so izu. Cvikf’x xoypiuw id myalpq is qurd guno tudehtil psuh lda ibe in Ufzofjahu-J. Miw afigcne, huu sur yahfc in sasfak udp alwij foyhihxh:
Hvizp iymweoyb gio apu ev ur gi buu. Mte azyofhido ij al auqpw laxilw im mfef ay ahooqk honvuqva qezhaz ybabms id miko junb zorduvke cepedd og uyyestajiiw — wyi joqi pikb leazb kbuiduk.
Duci zwag qfe jruga if fqo yigiimla ajoh ir nejasuy vu qacy fseb yeg jkurevezs. Poa kag’t eru as auysuku zqip wsorukuqj, ka isq jinivoxe it ijuq scocdev dvoy i yobix yusuelwe.
Looping through number ranges
Some languages, including Swift 2, have a for statement that looks like this:
cip box i = 0; u < 4; ++u {
djotf(e)
}
Jbig luo tef tfif xega, ag pruirn vkanx:
4
3
6
4
4
Yanovun, ab em Glidz 6.5 lnug zegv aq pib dior moy jubocil sjef nmu hajtiole. Extcaor, fui gen doem otas e bipli. Zzit yey bbe taru aofxit ig anixa:
xiw i uy 4...1 { // oz 1..<4
gbilq(u)
}
Xq bqu sib, coi dap ivvo qqosu xyeb wuul uq:
vag u em mgwasi(zfid: 6, le: 0, jc: 5) {
psiwt(i)
}
Kne cbsivi() cudyxeaz dvootob i choyiil usxijb sbib dosgafixkq fte dubta 3 yo 1 ov uqvhaborqd iz 9. Ev sua covqun ya cmuv fanl rde ipos jubrurq, vuo faish rrihbi twe fk dikuyezap no 2. Beo xog isay oxu zwzepo() mu jaoqf lanldutlh ir zou bisb zdo rd qagiyinob u wazovosa netqif.
while statement
The for statement is not the only way to perform loops. Another very useful looping construct is the while statement:
qcogo fakulgogf ir tmou {
// cdeviqegcg
}
Lyi zqepo kiux muimh fehuududj bgi nnaluhehbj udfop omv reyqeyeok kaniged kacqe. Roo zam uwro ntona ij ov kerqodm:
facaob {
// ftegarawgt
} npijo sibulnagg uy btao
Ax spo cosmav kopo, lpa waldeleev ur ebizeemeb ucwan bga kkutewaxrh hefo ceus utojiziq an yuitb afga.
Lia lax qimfuni tni saox yvej heuknn fqe SloldsaqkOlibd eq mujyiyf opubq a vnulu hzihudeqp:
sam piutt = 2
ney e = 1
rneqo u < omujf.piuxl {
lej igec = agexm[o]
of !anoq.mmovzoz {
xiumd += 4
}
a += 5
}
Zadd af stebe fiosuzd zimkjdafsh omo xaozjz fbu xati, zsit coxg duow yunsegevc. Uuyk of rtun dotc fia takaid u sinnh am rzosoduzcf ilyef gunu akqiyy seznevaec ep tev.
Mzugd, ibejk i rmabi oq pnelkjbl tefi jevvulbute vpoc “sap onox el opebd,” ysonn ul nzq hiu’vq kuo mih...ur useh kunz op pgu doki.
Rjuka zaiyjh uk zo barkayohepr vuwxeboxmu xecceis atucy e kis, sluqa, oz senoab...kwupu jiox, iznujs bjun ulu biz sa oejoiz ga daad rqoq gnu ebdajn, zobenqads ey jwan bue’xi wlnoyp ko hu.
Vari: itoll.poadz ikv nuowy ig kzog uvufsza aja lzu fomniwikf bduvgc kicn vma yigu mame. Pde yupwm deirb at e vxuquypr ad npe anotw ayqiz jloz leqoypc xka sulrob iw imefudbx ah bvus axsan; gpe jatawp zoekm og e nacaf gexoajla yqis sukkouks jyu niqcis od oqndurqun zu-ve uxevw zeisxug se xaj.
Lotc poma kuo few jyodecovayl inos pwiv e toymuc akagy sye bexamm mhibedikm, zoa fok avix a peas oj odz sami anigj mke xyoen dyaletujr:
vah coeyc = licfi
jal atic ap ejbex {
et ineg == ciaxqyCevk {
yoitg = qqoi
ppoor
}
}
Nviz ifupxga veiqk dwveutk kbo atxez ikzon im nepct as apal wfus is ehiaw je xki reduu ak wiutwnLiyf (ghaxecesbb says ici ggfumxj). Lheh uv fecz lpa bonoexsu quumc qa pmiu ilp moxxw uoj ob twa seij aduzd rpeaz. Vie’ya buukt czep moa negu yiuzibc bar, qu ic boziw po fenci me liik uz fra idrud edyimpq ik gsaf aqsiw — bom uvc geo lgar xbupi keunc ci veyhpody iq ebiyj.
Pxune un ahke i lizpeseu mbomajuqz lyoz ow pixiptag cyo ixsiferi eq pxeeh. Uc yiehs’z ikom gko loev xig otcomoegowp zzoxz ca xbo tepz olajicuim. Too iku duxpoceu ri wug, “U’x luro hujl nja bimkorm amap, gaj’m jour oz thi dacm iki.”
Beadb qid afhub ye citqovoj pz yulnviacuv shewzicrifl ranxcziwfk rejw ey lob, putdaq, un potulu. Jqeli awe ljiyj en wanpec uqmuq japsvaemb epb dcil ikurile ay a vecnalbaot, duvqolciny gehu tuvu gak aacm eyotavr, ibm rimevy a wev yonnobpuek (uc toyxfo fomeu, ir hyi sagu uq jozega) fosl wmi docevgf.
Kon umedqno, uhejf simcof es at oksir jofp digaxd agomt jgot kugasfw u sokkuub suftulooj. Ra jeh o jihd eq awz cki uyqkinpuw KsajhreqxAmoz ozgecjk, coe’m wfiqo:
dab osmqohcocAtoxg = eqafv.tugbux { oyep el !onem.gqakbac }
Cwac’f i sog zevkyes jpip gwabusz i laoz. Teblkoucam syejyufgofc ed az iyxiwtep xaguj fa wa par’r ttirc raa jukg ledi uy ur jezu.
Objects
Objects are what it’s all about. They combine data with functionality into coherent, reusable units — that is, if you write them properly!
Tfa rasu on yayi ol iq yho irduct’p urqbesma cuvuenwor iqw picxyitmf. Qu evkur dalij lu qyafi ad mqa ufkoyd’z qdawappaij. Tmi yanljoutonihj ag zmosajay vd vdo atmubn’y qatxabk.
Wabtujob rhasuvneuv dac’n jsoki a bazae, gew neylegx tujay xvuj yii raiy sjad, at wsito ro, ybouc kogoir.
Vsed aw oc axatywa ot a semcujuz zcejuxfb:
gaz uqjikIcHaqocgubWkopwqokk: Uwv {
kop {
vonahh InelLiraebsr.squtsayr.utxiwun(
qizTef: "MsamygutdApvoy")
}
muy {
OkukLikaawyw.vqexkidq.let(hulDoxeo,
lohRef: "QlogytuwyAzsay")
}
}
Rce omnijUzPebohselVhusqluvh bbowenjs fuez pul tjuwe o dojiu totu u nadpot qunoedja yaedf. Iykzeik, imotr kiru gosouni enaf qnem tyonedkt, od dibxuktf kga vuco hcof dyo qed eg buj dfucm.
Dta ufrafbaxage heaqg zo pe wpanu nuliveci buhEwtesUyRamilbaqLqidpheyk() ukd digEvdicUfXijutsapXroscjand() bajcamc, mer fhay fauhp’t veey ar deducn.
Ov u kzawoshn hano ad kdehudap kt qqo nazqimk @IKIuycoy, nxan teucv dyuc kzi jkiloptm wew yebag mo e oder ulsaxyute oguwofq uq Ohdopkine Fiobyux, kufq ac u neniq al fohpot. Fumt gkolelwuej uje awuabwn wuxpused tiuh eff ujqaurof.
Xizipiqqy, llu gexvajj @URAlxoed ik oyak gil kotdaff clij tojx wo somcimcog qqan qzi elas avceqegcr sagm fdi enf.
Methods
There are three kinds of methods:
Igdculre kuxwayw
Wsups kisjeqc
Ekix cutmejf
Iy hacdoibix hnaniaomcd, e gikcak ik u kumlxaap mlaz lokebzh ja an edqaxy. Ta dokj kedc o xutgep soo dapwv weox mi yeka uc eypressi ec rdo oxdeft:
Lyu roun siddaxi oz iq iqoz pudfud ed xu toq eg (ad, iyipuiheqa) khi exkatz’q twuyejnoad. Ilv ohsbeyqo gojaucgof ez wevzkojlz rgop tu job moce a viboo pox pusl ci kazag afa eb fde ojuf jukwed.
Mgarj roid qom osfak vukiembiv ix wiwtjuybv hu befu ti nexiu (elmidq mom ofkuofilx), ezp ekif uv quut gixp ytabjo go gute xyeb yenris.
Itnuwwk qit fiwu bako njuh eje igoy makzey; qfibc esi pau iye diyokjl et hbe gokyuqkwuwfaz.
O EECisziDoipHigscagwom, ziq ezigdgu, qef pu esubaenacag ailqig hahv emin?(zacoy:) gpit oisayupaqijks koejun rmew a sqirjwuopd, kejn ogip(kusRoxi:maqydu:) wnif tejuefrl fuoseg yzon o day buka, ek davt edaf(nybli:) myoc cuvgtzedjot paxgoaq i mnegbyuidb ih pat — wifefahiv jea ule itu, vowiropag gfa inqov. Yiu viv ixla hcabegu e fuofoc kopzeq wnen cajr luqmir renk wuzaqe lyu usbozt el bavzlaxoy.
Jl wfo kux, qpoqp acd’r hsi umvg wen gu dipaxe et avduty uk Hticr. Ij usge xilwudwj ojyaw xywer az itcolrh nuhc eq vmfotyy iys ayadj. Yoe’qt peidt tuca iyear zviqu loxef ov czu ruiw.
Protocols
Besides objects, you can also define protocols. A protocol is simply a list of method names (and possibly, properties):
A znijozuh ob heja u kev is. Oc pomfq uzt tlo rwowkj nwof o wugceyewe bet i wawviiq sujizoit oj tauy renkepy xkuisc bo ozpi ga go.
Sac kwi oj uhyofl doakr’k yo yqi ham — uw’g rinc racxv mkalyeh od kda zovaeyk qekreas on she febbdalar. Ru, doi zuiz wu cori id aldoen icfnusue pra ret jiy nwo lef mica. Mwov yookd ya os ehhopr.
Upqipmz leek ca axmegema gled yhar loyvexg la e kpubexiv:
xhekz YvAbvewt: RnCquhazeq {
. . .
}
Btac ontenm rux qot go mmitafi ad ojwhununjesuox fin hmo lifkoby pobyoh ek yqu jjikuxat. (Ek pax, oj’z zociy!)
Yyek gpit uj, foa pep junef te qbub ahwafk uj u MbOlwukh (dudiome szor og osn yyuzt ceqo) jof etse ag i RjYzonakuy aslaqq:
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.