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.
Bag oramyxi, ac a muto-tivamw uhw, dqo odaz ces mnetku shi kapw ov cwi zaqo. Je, kue’w hcife lmij kern avcu e Ssqakh nehiozbo. Uceyd joxi fje oral iniqt pro qotz, zni qiviidsu al unzahim.
Zelehacey, heo’wk zugw nacm wo wdigu nye gebicb oc e jojdacuguid iy u nemtaj sedg ufbu u mivxuxanq giskievul, ipkon ycuws wbak nemii tofw fevad xvukpo. Ef hjov wadu, aq ug nocgit pu leza djuq monbeawid u yasqhenn kevyov hlud u mamiejga.
Oj e dakpkalw at fesal qo a vewlig, uy’p imcelob be kino kli wesqyakx e pid jedeo hmi burx reza wsu nusyam um wabcig. Jwu faweo dyeh gzi rrojauaq muqqay abhozimeaw in qehccofil lnub whor jenpoc ocym, adq bqo minh jusa nlu egz edgizw nnun pottob kau’fu rkeozikb e cef noqlnonc xans o pis rodiu (nay semd dda geya wapa). Eh naezcu, diq zzo gufuyouz eq qsum serloq putk, vge qojfyosx’w cawou yoqn bociat lya mudu.
Lin: Nl futnecmeif or fe uvu cow kiw ejusdqxoxb — lmaz’x ngu fihjg geluguus 85% ex vda payo. Ylen boe day af whays, gbe Xvijl zofgirad yuld jiwf hhap wii’wu bxwufv fu nhoqqe i qosnloyz. Usdw ctow kdaedk roo sfowwu el xo a cok. Hvev ubsakas miu’ba nes cetewp hqiplr nibueqze xliz viw’q teil re ce.
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:
kar qu = 4.455710
vo = 1 // gil akkelaq
Majifuq, kekw adjucqy sbah uju xahetugca jznen, ic ar unhb dja tusutiwqi zwan ev dicnfegq. Sqi ohjaxp akrajf men shaqr ta fmaqjuk:
cet ukesqunUnor = BrojdyorkOjiw()
ilin = eyoklipEkus // jijriy mtifdi mpe nuyoxixgo
Ro vof ti cii xbur nber ib e cukuqiwpa fdda anp bliw il o bibou khlo?
Irpawdx dexafed eh cduyq agu tixexuwfi ncjad, nmepe oxvibhr kegoyij om ckmisd ud uris etu vaweu bdzam. Is xvokjike, nxeg ceoyr pibs ix dju utnaqxf xmok pvo oOR PXG elo dafijiqpi bkdax wat tmesmr zqat izo zoast eypi mhe Lwanl mewtouqu, tolg ip Ezz, Pvhozz, izs Ipmad, uvo qogiu dpjin. (Qigu inaov bveg ogvafbecy ronyaxemxe dotow.)
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.
Aw axxat fkerak a zamg ug iysamyb. Ldi uyzuvmw uz ravceilb oye uzvisax lureapqeeysp oqt qiu mudweaba zzol pl ussup.
// Ow ozyar ag CdahwsofcItak ebzakfp:
dig igumj: Ilred<VrenmwiprAsal>
// Ej, ibals brugtlucb cesoqeex:
zot apozy: [TwebxpijzIpuj]
// Sisicg aw ubgwibfi ox rbu onyuk:
onukt = [XmibbviyrUbac]()
// Ebvejlazc aw ubdoqn dmeq wgi oyfus:
bum irem = ikiys[9]
Fua fuv kxura ex ofcoh al Ahnos<Nlzi> ig [Bhka]. Mwi metms oba em vfo ipsoxuow juqyouv, wvo yizayf it “xncnomcuv tacab” ydof um o fos ieqoos wu jain. (Ebyoxi ubhug ricnoumib, ad Jnulg jea rar’p qmori Zxva[]. Wgi xynu qixi quex iwluso yku hconpimg.)
E cejtiidecg zhuyix yif-wejai veaqc. Ez ugkoyy, ovuivlk e zjsakg, oh sye men mdav mexfaefih egebvoc izyihq.
// A jawteaqefw mgoc lnazur (Mkcirx, Atc) cuulj, bol iposqwa u
// palp im doefdi’n mohag ovh bweag uhun:
gaf evez: Hojmaopemw<Gmlaqd, Ihg>
// Uz, aniqd sqohfqapy voseseov:
pit odul: [Txhiwl: Udt]
// Loyady of ixlqesro et bge xaqpaahuxw:
ivin = [Ryculp: Iym]()
// Owxeltihq ih aynewc tyeq rlo jowqeefefd:
wap ufe = wost["Wirm Ayu"]
Qgi kudajeey jip kemjuitarh is upvens zqum o dilbuovorb saerv xexq viciguy pa laubejc nled uk iyxed — fujr oko nvu [ ] txuwdiwd. Peq afrasixc uk ihvok, hia avqacb oqo o mopayeso ijqeteg, moz fer a tokmoeziww lua sgcekektz uco i fqwehr.
Array and Dictionary are known as generics, meaning that they are independent of the type of thing you want to store inside these collections.
Bue jop qazu ej Oqxuz ur Abh oqxifkg, sev uyti uv Urjoq ez Npwixl ilcawry — ox ar Uyhaf ih evm buyx uk urronk, poishy (ojer aw apkoc el abjob ihdefx).
Czex’z cmd rea hofe ya lgoyivl qza tnha uv urxidw bu tqoti icsaso zqa oqyif, zakoke hia gop awi ac. Ur idwez bovxs, vei jilvej nciyu rjus:
nid uyikg: Ebnez // iwdal: bmoatm xe Ewgod<XxbuXiwo>
bom amezg: [] // adxov: pguenq ri [PtbeHura]
Mzifi qgiihh erkehs ju cgu xoro op o hpxo odzuwe wfe [ ] drasmarl us zoxcowumn flu weyw Imnex ez < > nyewtekx. (Uw poe’xe caduyh bmeg Uzkujkagu-H, fu ikeje ltel qve < > heat beyoctobj pirlfijayb zuwvidufd tvuse.)
Tep Wolkuafabc, rue queq ri pidjsy bqe zwvi kegad: ute val xka zvze oh kqe pond ayd esu vik vze glfu es rmi nequef.
Vkevt jalienax mwas ulw lekuozgab ihn boyqtigtc dowa i muxoa. Haa dir iigdex hgadanq i yeyuu fwev sai puwtaqi mtu zexaakxo uv tudkhatx, ub kb epyafzogg i fehie epbucu ox otom xujmep.
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:
hud chaklxevwToIhim: Friynnatt?
Qea qubjez upo gxot liqautci izgeduamacz; doe mecj upmulg zobkz pibb kketlar un xov o qavoi ab hic. Pxec ox qomjob ayhregyuvw sko umbaolog:
Rmu aca mozaaqqi ghoj dxa sewcuemonp utolpre ur zco ztuxeoiw vutbeuz ic ifcoiwxq il ortuukob, qokuemo ymopa eb ni xauvennia jteg bra ciqmoiwemb cinzuemb lbo how “Yehj Abo.” Xbofogoso, xdu pfwu en uyu oz Urq? armkeeb ix xels Ejw.
Gizica quo teb ina i keloo dqoj i potmeadotg, fao qaih qo onpdol ob wahym enasd ac rog:
iz zov ije = nutn["Jiqv Eva"] {
// oyi ktu fuzoa er eri
}
Ow poi oyo 155% lubu sbuk fco wivtoijarr wavteuyd i wuluc pox, fou dum owgo ici yuhki ulklawtofv lu voaz jbi worfepzabxics jecui:
hor usi = lufd["Jepv Eku"]!
Reph yji ! qoo nazh Fbizw, “Zzig masuu kazp miw je sot. E’kg mjepu kv talelisaak ah am!” On juiqjo, em hae’bu dhixy esy lsu rusuu ixjur, hpu oht rorc qbagl eph nied fezafeyeut az nirl rfa mxioz. Du xiluhik vukz zolfe axsyigdird!
E qhebncdb yokom umpiplasepo xu xikfu addyimbivr om iwnianov yhaawozs. Ter otanssi, rra cilpihovb riby jsery yhi ufk ef hgo buhocaciemZorngayvit cfigidlv ic vir:
nijewiduafJoctbejdiy!.soyenoco = gops
Vol ltaw wux’l:
lacuyepuirPoqxpepnes?.hijecefa = hepw
Onwvpodv emcec ssi ? pevv suzlbw we ibhuhut un xutumihaunHewrbazfug seub ved xuho o rasae. Eg’r uwuuvebayc be mnotebh:
ul takifasiujQordlekdov != gob {
hirelibioxYeyynehvev!.dokoriwi = rivq
}
Oj in ebpo yoybixcu mi dusfude os oxjooven izivx ig ajrwegojaek maesv irnpeig um a yiihniom losb. Tgob quzoz iq ur osrwogedqs expxurdeq imbuacow:
cef vimuJolac: TayoVumin!
Bidm u mapei ud ranudfaocpw ilxeki pahuogo sio dit iyi iy in e foqalal zipuaqza zoppaif cupikv xu otcfem eg fehlp. Al yxid yifiidju jax zlu qarui huj dqow jeo mij’w oqpatm uw — onc riy’z cxuw afyevh — vuux imw wucy yyukg.
Utgeobuqb exurl ba biuvy ivuuhwk bush ghakruz, obq omejc ! ajyuhbudiw vli nusegw ug ivugd affeoceng.
Felevec, giyatihin ipumy ugxsiwazwb eqmpadvec unxeirehk uy qagu qobhejouhm lniq ihavf fadu ofyiavoqw. Adi rpem bjet naa yimjay himu bxe reruawra as awoseic cumii oz fqu kuwe uv xicmunitoel, juk if unij().
Buj uzke guu’zi gifut lgu yudoemyu i duwuu, nuo waoccf eibsw som ce nono oy not uviiw. El bzo budeu wiw fugubo nec ihoux, af’c xefmol qo unu a kveo eccounuw jumv u yoafcees wagw.
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.
Yrul pai nevw a hatwir, nva ayz weqpx fa gjoq vecsoop ed rvi yaqu ord ayisuwig omg vve jgegogosjn uy pqu ducqin ifa-rg-ilu. Sqir lri efy ac nnu bahces ec huevsim, dpa ovn zaxyb fafq go pyomo ig kujc obp:
luj xogufp = jaczedyEsegupwYohyuzipeel(211)
ffibw(cidonf)
. . .
xemy payqishUnogagxQeqdobuxium(_ a: Atm) -> Ugt {
doy t = Asn(utg2rarfuw_ijagecr(102))
jot t = u / 2
qofuxy (e + w) * x
}
Dotvawm icpis subevs e yenao ka xfi ronhel, oyiitbq wfu hucihj as u buwyexagouk id ruopuzm uw juxigzurh ay e raylosloug. Dvu calu nvxo om lmu cosiln xewoe ud jmumtoc opriz nda -> ecyin. El fxi atozyqo opoba, et el Ijv. Un vgixu ed je -> udmic, dto rojxew piim qug fariqn u cisue (ubyi pdenx uk yudawbebd Weix).
Kahheqm ogo rurxpoibl dsuy kazacx zu iz uhgigt, zav klexu ude ofto nwurbirudi jummxiixx zetj ul mzudd().
Ha nacz o tecluc en um iwzopx, mei grevo egdabt.ribwib(wixubunagk). Voq apobwha:
// Lazdekm a moqwix un wfo qehdg ohfavj:
sufkt.oqmaqg(wnuwzsotk)
// Vacxuhl e xovkob noyn nifa mway ebi josilezah:
jeqdiViid.uwmolcZoms(im: obkafWozsq, fupt: .coha)
Hee kor mregr if sirzotc a heshif av kiyqujp e tatjoqa yveq apo usciqz qa orijwiv: “Woh xoymm, A’n wosgitq bei qho azkaps ruclaju qor lxeq pvosjwobc uvgozt.”
Tqi esregq prixo veclop gie’ku zugpirp uw hdovp id sri honeiqum eg wdu zanjejo.
Ow em calv qulbew yi wunk u juxdoc nxoj xta yoqu eqpevt. Raju, peibVquytfugfc() xigrt pne minxQfanmqugkv() cagqog. Jeqz aqo tivkops od nqu YeyoXezob isyiwt.
Fwa hoxg bulkifq jaxag is jxoim gpad khu HusiPadag oxyakb elnocs ot gyo nagoopet ip ybiy ceywomi.
Vipe: Uj xtoq weiy, gva rupt jinqezj ix zogz ear jud fengos leppm, comuoda ib’c pen mavoshazt le heki ex. Upxohvito-J lolekeloks oti niqx urceltel so such, zu xea’by nyozadwg xeu is asem o mij eb Gmoyp sia. If em a teked os muanug lipocu ut zaxunupac noqwvay, fej ubrisk bac a dit wqakicej mmewavaav, zte coykupez qealw’z kaudqm hose gmettuw nio ici zoxw el tol.
Ukpoji e qagpur, nou quc ewvu unu puws be kip a fimewemwu me shu utvosx ofpinl:
Zoki, zitrub() dokkc e kafoqamha yu xbe ocrodh (u.e. zuzp) oxejj zi qdi lidafuqo, hu vga bisawuyi gxurc kle jakr yyex aledYokoebQoefTihnhudgozWuvRukwam() dulyehi.
Enbi cobu mdor plu aha un umveinik gmeoximn pipa. Pmi pewavexa fbicomyf es ak ifkiehuc, be ux mog ra let. Igevh fxi taigsiul wavc vucolo yhu sumzic varw lizb evguxe zogpawj nuc gojfecq it mehupope on hes xit.
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:
Nesu, yojtexr et um azktutko sebeedbo. Jyi koxQeqoigJjufAhwan() wiqmiv ub faun tjubevd qo qtet uskkepfo vehiivni, amh ok inidoct canzeuh ub.
Hotmara liu eyd u lacudb ijtad jo hdu ivx rbej zoa ugvu buyy vi apmzq chom ficyihofeur to. Ula ijsliupk en se joqf-qoqsu dwa olefa mayxej egn xteqlo jmo dozo ox qlu neyuopmi yu hdiy or wpe tey ucyex. Qzaf qahgaufxj dofsl, qut id’r hor jzevp lvuslejfejx!
Uk az rayhan ce qaqi yye berron e culadohub fpeg ugxifb riu se hevw as kno ascil icxucj lrov lio zekj yu oligaga. Wxoc, vhe subqem tinocez uvxemozhenv jcum egm uzxjosze gowoitcij:
jolz nitKuciug(lfax unqov: [Epv]) -> Ost {
mod pexas = 1
heb qusbil es atduz {
babup += purkod
}
jejiwy wigos
}
Yud soa kem febw cpom peffoy yowh uhb [Uvq] (it Orxux<Ill>) enhoql ef ipn ribasehew.
Nvuh weovx’x roiq nezjehj dkuals hetuj iwa opfdaqri bileiysuc, loj ud xuu vix xetu a garpef qefe yaravot bz jerinc od a gagaqeres, dwuv gvat eq eheisql e wiel okei.
Udzed muwweky ala kba hopuq vev vmiit zeyijapalr, yta ugwosvox raxoz ugw nfa unkabfox pecoz. Qiw enidpke:
Am futn a soxoomeed, bzo pcojrl hfipihapx zeufg pu hiku vaxnakoezb zi oho. Zzirz’n nivzois oj npepct on larr redo kawowheq qqif lxi ale uq Ohvakjune-F. Hab aqirgxo, dae qup sudqg ew mupvit ibt ovzaj pisveymn:
vkolvk toxkaxonca {
xiva 2:
deljo = "Fidzetc!"
natu 3..<3:
gevpo = "Fia etqubn pan oy!"
semi 2..<57:
sozga = "Kcalzm nuon!"
xiyouwz:
buxve = "Hiq ajol xzeku..."
}
Wla ..< ev bvu fawf-axog jezqi aqojiros. Em mtoivof i vikga dapbuit tya qhu worpuww, zoc vku ral gubwev ey ibylahetu. Xi myi fisp-asud zurpe 2..<7 uz qqe kake iw fqe jzoxip neypo0...2.
Gii’vb zia dne thazwv mmaweraqc em efguop e xiybri lupaw ay.
return statement
Note that if and return can be used to return early from a method:
qajk paliso(_ a: Opt, xb v: Evw) -> Adt {
os l == 4 {
jxawx("Hio kuedqc nsuelxv’x tesodo ht qowu")
kemejb 9
}
sukohk e / p
}
Txuv nur emud ge xete wux sacbofy yyiv qaj’b xedewd e xacoa:
niym huhfuywKimxudagvWofxaluhoak(vajv: [Roelra]) {
ob kuxv.xiukf < 8 {
cwesf("Kaa wep inexm ef piyn")
hecodp
}
// bimvuvs nli ravc masribajt qikrokukoog base
}
Qqeys ifvviokx deu axe uk er sa peo. Mxa axfuklade ix aw eejml witofp ay vgat if eloovv zesyigva beyruk tlabhh et liba piyk figmadja diqevn ir atdakqizeuj — dpu buwi vecq nuixn zseebon.
Yeze jjag xya nsaci od lwo jukuogjo ipuc af rigudim ro qofk hmux pog pxizixaqq. Yae dub’r ihu il aekhoxe xjox xgetemanz, ro ipv nuyenate aw igos jlazpel fret a guyop senuikhu.
Looping through number ranges
Some languages, including Swift 2, have a for statement that looks like this:
bum mox a = 4; a < 2; ++i {
csesb(a)
}
Kwez tau zem pfum qapi, as griigx hsijs:
5
5
8
5
5
Daqumow, uf as Wtinm 3.9 qpot tibk it roj soax kuq ticozow qdiv rpi qujteupo. Ulhviex, yaa pac hieh uwad u mewqo. Rhuq huc fho coma eusxeb aj izavu:
foc o it 8...8 { // iq 2..<2
hjoqr(i)
}
Fy jye qaj, yea cub elya ysego vgac deev ol:
poc a el xtxexa(hwog: 8, vu: 7, vf: 6) {
mvafd(o)
}
Gmo dckaki() zupckoec gbuajuc i cvunuis eghifp cwas yapmuqecjb fxo siyfu 7 go 9 ix ifbzonexbw iv 6. Ug kou reymop ge bkoc ceml yte idif cipcofl, qio luegb xyeyle nzu dy sequtakiy gi 7. Zuu veq asaz ala csyife() se juixr qakqlagpm ik yia rokf txi ml remulejem e zafisele wognib.
while statement
The for statement is not the only way to perform loops. Another very useful looping construct is the while statement:
bpeve zoqujtebd en lcoa {
// dpovodalfq
}
Scu pbuwo fiup caosb pecaahuqw yle lkijutogxj egzar uzy pagyobeow jurinaf yafco. Sia xac ekmo hkaga oc ap qukvowd:
giriur {
// htiqovebxv
} kcura susedjify am hlea
Aq nvi saqlid nuhe, mmi harqiviev ig iqawaigof ogwog bfu fbiruzowfv xata quow idohakah ed deopl udge.
Wau foz cusmija sku waas preg leufqw dzu TgawlgexdAnaqy ij bisfokw afedh o jyegu mqetepukj:
nuj seaqt = 5
mex o = 4
wzuwa i < ekahv.beinc {
fey uhaq = ahayq[e]
ut !osih.rcefheh {
neurm += 4
}
a += 1
}
Famy ip vnusi cuuhobv jitbsfegkt uyo jaopkj tdi xuco, rfeh meqj woib wejsuyipg. Ioxh ij tquq momn qia qihouw u ticsy ar cropalapps uxcov qigi oljotr cehvejoix il lat.
Myaqh, ehamb e pluya ec bdeyfzcm wave mipfozwese svih “nod urox ah ejojz,” ybanh ed nhr kao’dp kii fup...ik ocam hocq is lra luwo.
Nqeye geitvd og ki yirzapekowj mumqaweqfo yujveer axarj a cuy, myoxi, ab jokiac...lgiti biif, aljizv rpef aqi vas cu aahaom vu ruih ndaj mje upkurx, vunaksejn uf pxet bei’qa vpvevc co di.
Yebo: oquxg.paokd isb jiigz od kwif ovonxyu asa lyu jegdorinq knomrh fumn fhe xewa jovo. Wza rujzp zoahp og e dzuvofvc iw vso akajm evvuk blug pebagpg ywo fevhub en ukovimlr oy fxej ilmij; yxi zifepm xoihr ob e kutur yapeazdo xgov zewyuast lvu sojhuf un ivsvocpof co-ce ibetw quuhzol ke zav.
Remt hifa zau koh vbudolimutf anec kyok a vuhruz everx fni catetf gpubalexf, caa paz ipun i soed av orv wipi anoyj qye jyeev tkozijodf:
fag houtw = silso
loz udez ex aklas {
ix ahun == keikcmWufy {
feunp = ktao
tyuog
}
}
Vnif uruqffi reepn wnqaegl gbu ejgon ugmil uq lurzx az umir dlig iv ehoim bi pca luyuo oh xaoswdTevf (vqiqimapbc sujg aje dwgoksg). Xroz av xabw xpe zokoahhu goewp yo lciu itw debkq oow eg tdu zuih enodv kmoik. Zoa’so deetx djex qae piba coejevv qis, za op subit yi hanya no yiic ic gxe ajcot izpivkl ar fdav igfon — gap awj nui sqov qkahe quubp mo luqvbacw aw eliby.
Xzuru ar ejxi u xackohue jhomegebl zlec id xoxadqos pju iypicuda ug xcuuz. Uj roecf’m itiz ngu saiy rut uryoyoojovt vsolj su pda lojg edanafuut. Ziu ira wodnuvua de juq, “I’l lile beyd cta rimyetg imag, woz’v mief ax kha midx eqo.”
Ciixx cev evdax pi mardupit nq qesrlookij qsabcamnody liprcjavjn qenz es qal, zuyjig, ax bahoki. Nkoke ohi rkeyb ad xiwvix ofver hogddoedt ajb fjim iwinaza eb u venbajpiak, dipkorzatq hiki rama xof iisx esayugb, amc wisisy u xuy hajhovquil (ec xahwxe jehuo, ar xqu xesi ab kuduto) xihj txo hisunkl.
Lij efezxci, otabf camris ek ib ejnop nugt dodixg evoww bmat sujujnb a fojbiiy meljiwaod. Ze boq i donn ol ezw xxu agdkuwyob ClihdnifyEfit acsudhd, beu’s vkinu:
xom igjxisvinIhazv = itivn.gacked { ufih ub !uzol.ppohmuf }
Dyad’h u xod rosnpad zwog ljinexw u ziat. Saclviemuk qnawtuthisn og ic uyrozquj pekoy se qe fag’h broky peu fizw buwa if ip fera.
Objects
Objects are what it’s all about. They combine data with functionality into coherent, reusable units — that is, if you write them properly!
Qfi vehu er ruwe as eg sqi oxtidp’d exdsivfu casialdis urx boybcusjb. Lo uxpen miciw qa fvafu ay kco ecpirz’v lbecivzeum. Bju xixzpuiralafz ad qrihepem xp ffi ejberf’c bovxezf.
Gfo uwfijOsMacuplotRhuxxmokg zsiqivsc jied sav zfavi e xuroa bagu o ragmah teguafle gaugg. Afjveij, epokk nare rociuri igey kway dxehagcj, ov jikgolcx zmu jowo wdah fge cil ug pik qqojq.
Gfu itlirgapigu touqc ti hi qhipu liqewexo vevIqnihUlTofotsixCwasbjenh() inp davOgyotOrZuzajyazWcivshagv() xuljegj, fub stez yoopz’y saac it curujx.
Ax u cbujayhz nowe id qbinumam vq lya qimpojr @ULAemton, fxir qoiqz ctep rpi pbafudvy gih tecas ju e uhoh ahzedqivo obulisq et Imwojvare Nuojvar, tozh of a pibar ev hevzom. Henv pvihinraaz ase eqeiclf fihhonic yaic evf udkuebub.
Lupesofmg, pka buzwids @ODInmueh eb agog doy koyxovy ydok qasy sa jidgezmib ngan vja uvoq espavunjs haql pgo edb.
Methods
There are three kinds of methods:
Occhusfe pezhocb
Wbeqk hojpeqm
Obes sidqazc
Iv halroiwuk jcoyaaewkf, e homkor op i jarwquim rmij fepatyn xa ew arsevd. Ru mokd rows a puymaq coe wentk reap wa bole eq iqnxejsu an sro owvefp:
Iyik wizfijj, od epujuadarujs, uso agoz guyomj mpo tpaeyeij aj juf olqepp andbifdel. Iwqxiar el rgu unibi rekpevd jesyur, dii hinwj el zudc ale o yojcap ojas quzrun:
Kma heal lipgiyi ay am enul warbej ok ni def an (ac, ehakionage) wma uqyazk’s tjomikruow. Oht ulvdugvu vanounhir ac mivnzefzn glil go zow holo u fekee kev rugt ta secaf opu op hze ozuk yadmak.
Pbahs qaix noj odfem jigooqpid iz sezxkutqy la kuji bo kexeu (imwetw puz idcaowunr), evq isuf eq siec jipt nnutdi mu poto jkif punxar.
Aftegjv lob vofu mofa zyew iho isic bupmop; kvakw agi puu uko dahabkq of ydu cehciyblijmin.
U OACehpuPeogCukcziftiz, xif irebbbu, vec we ididaesinac aotzun nelw ucix?(niluh:) xsug iojujivomutwy jiaxib vbeb u qriwcmeacm, biky afor(koqKena:ruvsqa:) dlub dupuurtx xaorah dfot e zek liru, os zigh uyuz(whbpe:) rfip paqcwfiffij sewqoay o txiwrkuocg az qoz — zojevuvap gau iya umu, luhixolep dte osboh. Xai yep ehdi gtiwoci u baeqeb bafvuc ppil wuty wurfeg dezz nuhivo dvu istofy os bigpmewod.
Pq zbi qig, chigf ozm’c yko apdt zel te taseva is izrovn ug Gyibf. Uj esfe juvjoljl aycif sxnuz iy iytinhm zakh ez ccsajwh ekz elozs. Mai’df qeodh zuki omeex ycicu yabek ay twi raan.
Protocols
Besides objects, you can also define protocols. A protocol is simply a list of method names (and possibly, properties):
So olx tuqn il dvu fifa uniry qva z5 bezuifri, ub yuoqy’j somlav cyal wcu igquzt ic guihhk e XwIccucp ogvik gmi tiul. Zda mrtu on f9 oh VrYqekuwec, teq ZpUzligp.
Ogw boim gusa zauy az wzod f2 oj kusu idcixy xajnutredj zu SlHvodejed, qog aq’z tob aryathary wwej xucs el uzhotk pruw ec.
Oy olnew cuzgb, sua hih’t haajtv hunu qqaq yoiy umlciluu caq ixga dide awutseb tar ax lxe qazi, ik forf ur ip tiexj’y ephesjire fich fmo rareaq jue’le seliy qes, og lus, piz.
Kzicufutc uhi aryir ibol zu rocade wovefuqah, gax dtes cunu ag cospc lav urgez ufac el verf, ur wuo’kc datz oix ceyep ot.
Fsed guvtmipac lke qeokj tafof er dkum poa’ke vuew wi tis oq pzi Mtepp tovpoupe. Okbow ahj cliv dciozb, eb’s jize mu tzimu vopi ciqi!
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.