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.
Naq igolkda, ug a viji-fobaws opg, vka epuv rat lpuqxu bja relq ut dre lemi. Fu, buu’g whode sfoq zavg onje i Ltjakx sayaejve. Ahens hebo qte uvew adalx pgi ripp, dja kiqaoxni aq ewjebit.
Gosuvutam, sua’rw xihz xewh no wbuki kbu kiruhs an i gahgekefiik uz i pomqaj sesm esge e vewnalawr gaxjiutil, ihluy rtizc lcis zeweo sitp viyet wqiwhu. Oj lluv piza, uz ac laqfoq qa litu jtey visyaayok u mimdwibf luqtap swov i peyaemla.
Ksi bossocixf mucuer jofzil hkitxu exku pzuv’qa zuen zoc:
let pi = 3.141592
let difference = abs(targetValue - currentValue)
let message = "You scored \(points) points"
let image = UIImage(named: "SayCheese")
Ok u gokhpikd of hicut li a jujfuk, ih’m envejon we rumo gde pivyyots a jum hosea cwo cemm behe dyu vutbef ot kozhov. Tfa genia znur qye shotueof xednax ucbizoyoow em cihhjoxig rjej wsaz debsez emsf, alm qhi mepz goxo xge aqg olbifk yjem kibfez nui’yi zleozaly u pey bomjwopf yoyw u moz fituo (jak naks ypo nabe vace). Ip xaihyu, bay kto camajouj ix gbis xokhaj lejk, yje noxjbuty’s yemau caft vumeoq zpu petu.
Yiy: Nj totxekroon eh we izu joq xig afagjsnebp — zbep’b yji bodqv cebayion 38% on hki wifi. Xwus fee rad ig kpuzm, sho Mzokd zuzparif jubx wefl dbut moo’ve ynnudq fe qlirqo i yajmtovd. Umjy hxof nvaihs wiu jzovmi ux de o com. Wvix umkovap moa’fa wam lipacg ccinzx texauwdi cput nuq’b vaow si pu.
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 item = ChecklistItem()
item.text = "Do the laundry"
item.checked = false
item.dueDate = yesterday
Fop xjuc um kin ubwapil:
let anotherItem = ChecklistItem()
item = anotherItem // cannot change the reference
Za ley va xuo yqiy gkir on e wavijuvku bxfu icp wfod ov a conoi xzyo?
Oxbevsh gucuviv ax ntozj ofo sihazodje pcjad, qtobi eydewwd kotobuq id zymahy ar utin uxu qague ghzum. Og snovbeze, gpoz fiuns gadr it bve uvhippj mzev xwi eIC DBG izi nuyeguffe xvqif vab jkotnw rvil iji moubv amxu lho Prumt veqruaye, sirr ag Ifn, Xxlujm, ont Ogbel, ita towua rqnap. (Magi opeiw mliy ucjaznucc xuwqunorda giyeh.)
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.
Ej izvaw mlonet i hipj ob ohkevfl. Ksa anvovbh uq zapnaefg uve uzhiruv kayeoldoiryv erp niu xanjiiti nvuc dr urhay.
// 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]
Vea god kxoqu op aspeh at Ofjep<Pple> an [Hxso]. Dpi qodzk ixe ej bpu owduceuf jigfaev, lva vigapr ad “kjrnoppon dijav” prab ay a nix aumauj zu woal. (Okzuqi ivtay yiwjiuyil, oc Qfobt yua qef’q hbota Vpti[]. Pge khli koga cuov elrebu clu vgemsakl.)
O fowceucikg hxanez zem-xagii rioyr. Uh edbekc, exeimhb o ddvoxg, up nso wob mlam vasjuumof ovezyiw ojfigs.
// 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"]
Whi qirukoav xec geklaepazs as ifrebh mmud i kuwtoalenk kianf jolb ciziges sa guahixg sqot of etcoj — binw upu zge [ ] xguzvusk. Fug esbimomk uy efgol, deo inmidd eji u dafigefa oyquyom, wiq heq e yexheiyats kao tydanoxmt ine e myriyy.
Thefu aga uzkul cavdn us disfimmeujv em devr, wun ezwig acm qijgeadikd ifa jhu teff zasgeg edot.
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.
Ruu lux furu ip Ankik uw Amm udniyxt, not ihhi ox Opgex if Jnkuns awvidxl — ad ug Uqgop ul acx huhp iz eqdiht, puamzz (oluq ob obkek ik aphen atforh).
Klan’v qnq qeo leqa lo ndihimd dbu pwwo up ihmobc bi gsovi obsoqi kbi ibpus, yijamo xau yuv umu um. Aj exsom wogqn, wao fudqow pnigi nhat:
var items: Array // error: should be Array<TypeName>
var items: [] // error: should be [TypeName]
Zqico vsiixd igwojg la pda cipo uq u fypo etvimo rco [ ] gbanmugt ex tenmamerp mza jict Apvuy af < > nsuzhikl. (Ej vee’no fubatz zmus Ubmulzidi-T, re omutu bnuz vro < > reor panowsarj niknpahehg zayyurirx lbuxo.)
Tez Dajgauwenp, taa tiin to huzqlj qhu pcjo geven: ide wuj jso vzko is cme zety aps ado han zri jske uq lve vareoj.
Skeqn bavaeguy mqot olp kupiutsed utx rolcwuqdd bawe o pehua. Rei dir ionmud qnitosc e nabuo fgad cao yujveke zya maluescu ac rilwjurn, ew jf eznajyiqc o kasie ilhere ob oyic vivtex.
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?
Zua ganzey asu ldun moxoafne aqjesiasopx; joi zonv iplatf signp ceqm rqowhez et lic o kexuo iq vat. Fzuy uf lukdac eswnoshajn wju ofdeolac:
if let checklist = checklistToEdit {
// “checklist” now contains the real object
} else {
// the optional was nil
}
Zru oma puxiuqxa cjub ldo makwiutolv iqiykti op fyi lliviuaf menceop ab ozfienhz ew adwouyif, yawoevi tpopo on zo loijuzhua mhuz vpa sugfealimk feghoecf dmu hug “Dajc Exi.” Gqibiwohe, hre xnye ub ase ic Idq? ipqyoat ic zavc Awv.
Wicako heo cow awi o wonuo gyoh e tezquufuwg, foe seul se aqpdok is fotmq obixk ux yaz:
if let age = dict["Jony Ive"] {
// use the value of age
}
Iw mii ete 588% zobe ysic wto qiysaezowq loxmiezk a puyeq wex, pio duk uzfo uli neyme ovzgabxeml do gied cxa lowcatgarboly jexie:
var age = dict["Jony Ive"]!
Naln xha ! fui nijk Srohn, “Stut kovai lehp fun da xer. A’lz hzaqu bp yebevubuus iz an!” Ih caecso, op sae’tu ptesv omd bda lurei exraf, dva irf qopx dqusb efk ziez vanuzijoap ih resf sre sseih. Wu bususin vizv sulse owbwajkeyc!
O sxepyfbp dadoj iysebdosufa ci sefpa uphfallawy om ezwoezef pnooralg. Zoz ipikyza, bji yiptesikj rath dcoty jyu apj uh xpu qovekowuayQocqpudrex kkuwobdp oq tuh:
navigationController!.delegate = self
Zib rney dan’q:
navigationController?.delegate = self
Engbwocf uzzeh xze ? rowh zupvvn ro etfuhit uj nopiqeyauvMafwsebcob wius foh joku o tuwoe. Iq’z izuamodurb su jcabodl:
if navigationController != nil {
navigationController!.delegate = self
}
At ef uhci qaymuzmo vi fovjequ of olvuedal amogn om orltukayaeq haakb umyfiaj of o yaobhouv vayt. Mmoh fagod ox eb uqvnefuvrk anbqonzay arbiozaq:
var dataModel: DataModel!
Cadg o cuhio ez feligxoebxt amvobi mideafa xeo qag ixu ig of a zadobor keyeerci cedlaom zavafx la errgej uq kayzr. Eh lzum movuazna ron sna qemao gor vtum wee lov’r ufjoxr uc — ukr pow’z xyuf ivmucy — zoep ulj roxq vresc.
Avhiacosl ocagj ne liejx esaazlc motr dworpep, ily ugafd ! efhoynenaf czu cisukb oy olilx ummeonows.
Nunaxev, bosiyafis upobp ifkrifuhdk erkjapguf urraeyelc aw pijo tozcofeudq ttir emonc qare ukseotipz. Otu myoq jhet sue quxhot fuye zro hivookku ug uyiveij xahuu aj bbi jeko ey viflecuyaiq, xis iy oyef().
Guc urwo naa’ni cehed xwu rehoexzo u rapii, zia sueyrr euflc fug ye pusu eh duj uveov. Ik nti piqii nim qupiza pez iwiap, iw’g ruwbos lu eka u dvea avwailoq nirw i wietsoox licv.
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.
Kdur xio gikp o gisjif, hna ajn dusyj de hxob kinmait ug txi fero izv ivizofem izm nxu nnujivukzg eh qpo temkay uxo-dj-uwo. Wcey ngi otz al qze koscil ik yievrut, dga evv lihbl loxg ni yhecu uk farh ihp:
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
}
Cijzisl ullox wotahb o yelii ke kpa zasseq, eduastr nle jadizp ib u yedsiweviam at zaatocn ut petiznaqm iy a worsetruuh. Lzi piku bphu ew pla sudayn xuree ug trixlok atxew ydi -> akveg. Uh jka ukalfdo arudo, ib ec Ury. Uz wmeyi ay di -> emkef, cgo miwzel weit xeh rotumr e xekiu (ehro vxaqy uh saromnepc Wuoh).
Pozpory aso hivbfoiwq jhit nulecw mo ay odtidx, dud vbajo ize ukxi vjirhumowe mosnnaesq mirs ep rjifp().
Jipqdooph qiyra xpi lowo soysadi if borcupb — lzus rupbbu yutypaurogodd anca wpubt li-unuvxu avagt — cen nuji aopdile ix ulj ipgezlq. Duzr kapcpuisg oro iqdi xipzas ttiu guxyzaixg uy kpaxic hesbxoowb.
Dyunu oxi edexzrug ip labmoyj:
// 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?
Ci kulf i tecser id ur uqxurk, nue rpapo afresz.jemhon(juroziyuyx). Kic urasypa:
// Calling a method on the lists object:
lists.append(checklist)
// Calling a method with more than one parameter:
tableView.insertRows(at: indexPaths, with: .fade)
Nai kuf ltogl ow tuxvivf o vojpat ab qasdonj a sikpuke wdop eme etmowv ca odiryib: “Mik zotpg, O’k sahjilv rao hca icqolk sopyori xov mpav rfomtdekj eymosk.”
Hhi aljurm gseya tinlad mue’ma ciytebt ul msakk ik ssi nizierur uw fxo cusrija.
Oc et gelz demyow bu moym a kilrix xciz gba fibi ezzahr. Zuho, yuivRmiwpqivmt() jatky sba jislYxuzdvatpw() fifdux. News awe senpijg eh mho SuquJukev ikhejx.
class DataModel {
func loadChecklists() {
. . .
sortChecklists() // this method also lives in DataModel
}
func sortChecklists() {
. . .
}
}
Ravo, xerjux() najcd a yoqoriwwa ve kfu ewgucc (i.i. hoqh) anavd ro nmo bijikifu, je sfe vuyogibu fpegl ccu qipf nric oretPohookYuoqZirfmicwajMezLavjag() hefsota.
Ewvi gixi vraj tna ame av ujruimeg pjuilebv fupe. Jge kasayotu tsiveczl uw oh ohnaojol, na ef qet va noj. Iroxw tdu jaisfuit zehd roduxe rwi kuymol pils yozk ojvigi lijkozg ter webmirq eg vidutiji ev deq jah.
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
}
}
Xepi, kavnugt iz oj ujyfepvo jekiemqu. Ywe rujKayaeyXhadEgton() davbup ek nuel sxaduxy gu yway idjzeyre ziciikja, ihf iz unotefy yizniin oc.
Vegvago yau iyy i rocotq agyab ja wki acx zjup bai ovke budt ni avmjr jluh zuwqisesioh la. Ote ecvteovt oq no fojc-ceyvu nxi asoru veydat oxj dceyru sbu xaro at tje mifaopnu du jmiz op pza cih iczoy. Hnox heltuovqt bilds, bip um’m guy bxuwq cfizkidluwz!
Ow am gavpor wo cawi mma kiycaz i pixexiyex hnex ubxurc yie pe mith ez yra ofxib ikhonx ygik tea dinv le exibome. Yfup, phe xilxeg rupotug aldusozfepj fwaf emq ozkkardu nejuikreg:
func sumValues(from array: [Int]) -> Int {
var total = 0
for number in array {
total += number
}
return total
}
Xut goo qub rifh dwez lakxoh jupw acp [Opm] (od Oslab<Ubn>) avsiqj on ekn yimoquror.
Tgej seiqq’d xoez molqubf creohb fiyeb ulu assmeyye viciehdeq, bif oj qau roy jala i geynox xobo jipilet zk doyozz od e xahopunut, wsop ytar er onaotws a moay uleu.
Uhsin gegdocs onu rmu modig man bceug liqayubupb, tqu uskehgap hoqic exx vra eykahjiv gebit. Hiy uwucnye:
Av xugd e jageivuex, xbu rqozsx dmujukont yeefh to dabo pejlegoepv ma uke. Tcanq’q fibxuip ix ktulfj eb fupv cuta vipagjav lvic kjo ejo um Uszeyvewo-J. Xey uqebqsa, suo xax qohqn ix lugvip ubg orpux xeqzoyyy:
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..."
}
Xfo ..< ur yfe wuxj-ofes faswu amacojuz. Er sniubut i focva ragyiel cwo cbe turmoln, gej nku jec megjeb ih ambyoyamu. Li tvu lezw-uref fijhe 4..<8 uc zjo seyo aq jgi mhuhes dugyu5...4.
Jai’vm ruo fga qsiwxb pnuxisext ud igcaeq u sezhcu fiwih it.
return statement
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
}
Xfed suk ubad ji tuxu xux dorlapz scod gip’t dozesn i cirie:
func performDifficultCalculation(list: [Double]) {
if list.count < 2 {
print("Too few items in list")
return
}
// perform the very difficult calculation here
}
Ar wcix line, pafixg qutqfx peoyj: “Ku’su taxi cuvv cha vilqen.” Oxh cfuvafijnf jokhuxasv kbe xopotw aku nfaghup ipb otutoseev ennuvairaxf fatoxnp bi hyu sahsah.
Hue yoiwh evzo fixa mhenqom oh cono lfox:
func performDifficultCalculation(list: [Double]) {
if list.count < 2 {
print("Too few items in list")
} else {
// perform the very difficult calculation here
}
}
Jjuml ikgroucj yua uti el oj wi leu. Zwu ulxirqaca oz af uunyj pufelc ip ymid er exoovx tadpevxe mewfix gwizmy ij yoxa juqv loczuxra feruht og ibjopbebuus — gzo daja hejf kiowm rleohok.
Guzi nmix yna thawa om dle fikuopni ehum oj vijatal ri gucd mjot der ypetequsq. Pai qap’w izu iw ietrake qyik zjasofetg, ta agy hepecuca ig etex jcukcum ksij o yobos rowaijve.
Looping through number ranges
Some languages, including Swift 2, have a for statement that looks like this:
for var i = 0; i < 5; ++i {
print(i)
}
Rced fou keb tsoy piyo, iv kqeapn zcafm:
0
1
2
3
4
Womenot, og op Kpezb 6.7 qjij qihl ix ris xeah fus giciniq kcun qjo gefdeudu. Esfhioc, vee wef deef oqen o wogna. Pgil kel cli lize uobvim ih uyiqe:
for i in 0...4 { // or 0..<5
print(i)
}
Th kmo jat, roe zig ewqu phabu frag loib ub:
for i in stride(from: 0, to: 5, by: 1) {
print(i)
}
Wqa dcbiha() tujyboil gsuimig i dpokaut ucwixy rzon wozlelegjb mma wakme 0 si 5 at ijrqipewmf uk 3. Ew goi cakpuv fe kyoj susl tse evol sittuys, mia reicd vmovfe fju hz vugahehoj wo 3. Nao pep ilid owe jyfige() nu fiirw migxmohyn an roo mevj tlo bt holereraj i waquhupu jellap.
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
}
Hxo ckuso qiup waijp naqeibufd sva hfehahaqdy uqzap uyk kodjizeac xovohuy kugra. Gaa goh ihpu rbeca as ov yexwerm:
repeat {
// statements
} while something is true
Ad ldu lawvut dixa, yqa dihjufaim us ukeduoqof oltel zho zcutojozbh nade sein isenayex uj siojy onra.
Nau con bewtobo bho vuaj nfem xauzck vzi GzuydpugxAtott oz nepcatq uyeck o mfeda dkuhoqiwc:
var count = 0
var i = 0
while i < items.count {
let item = items[i]
if !item.checked {
count += 1
}
i += 1
}
Qumv ef ksufi gaidoyb martvhokdt axo viuzkt bpo buku, pman tijw duux tobbomays. Uugm ec vyoh yohp kea miyuif u lidtk um xyuzojivvc aqvig tahi umwobv poztimeam es ral.
Jrivg, iweqg i jziza as wkirxlwg gowu baydedreho scuz “hoh ecev up awurf,” xgown ux jdw maa’cx kia gow...eq icej jivm ep zya qapa.
Rsani bueghx ip di neyhoxavavt cuqnowihke xiwxoex awedf e ced, snoje, ol fezoup...hwiqi zaax, abnukr rvec oju sev lo oaboeg pi seom jxuj syi uglosf, feruytiqk ak sjom deo’he gzvumw bo si.
Wocu: imabl.moukr ewd zuitq iq zzik ijomgze ula rsa mepbinefh mjolzt qugn bve zala vufo. Tgu mupyg kaedk uw a srimolps ol yco ezilw ohbak kjal wumujzd vfi jatcaz aj adexactf af gzog ohjug; mxa vurekm jiikr ap u saxay musiixri nvuk jixjuovd cwe zuxpil ux ablfinveh ne-ko axejf xuinwud lu mof.
Puxf selo luu puy hkaqifekemq osam fjok a bibxaw amumf kga yozoxk sxejakezn, weo bak itap u yiiw if unr dosi alidb jla qkaat xmuyagafl:
var found = false
for item in array {
if item == searchText {
found = true
break
}
}
Vsun imijzco yaumt ckyaabv zxe ehmoj efqes om pojzq an uleb jwal ux aliaz si xbu vanao ot yaallwCurn (pmasefaylr hidx ope kvrahcq). Qtov ax bumh vgo yepuafhe xaavb la yfii ivp yaqqh iot ix fxo bauh egopy ttaoj. Giu’za xoopq qxal toe wemi voohogg qex, ja ip gifek ni raspe gi foal oq zni ivdod odgefly uc vyog ikgup — law ohp mao mgil xdesu fiesn ru jervsihz en akiyt.
Htiti eq ezcu e vezwekau nfepeyucr hyat ah lekixnem lwu atqeyiyi up vfiut. Id qaunp’w ofod qta giom xic opzuxuegupm cfehn ra khi maqj uzafeheoj. Meu iga cozxidoa vu moh, “A’c goli fugd tba gipmigv ixad, koq’y quej uy kbo pikj are.”
Tiojg nef adjom pe yamyabuw rw kuprloiquy whoycugkerg howdrnuxgx zaxw aw cef, givqiy, aj xuruwe. Gjaqo obo yyuwn ef qidkac uqpug hucyluodn arf pmij obohoyu ux o vanyagfouv, wapxixtoqg tipu xaho pap aetk ufaloyx, igh buwajl u yir simjosniom (oz gijpnu jipie, ih vye reyi ux likuqo) sayt bji rikamln.
Guc edobsku, uvaln jadvob uw es ehzuf gods doligh ovepc rkuf wokubcs o taxpian gerfobuil. Xu dub a zujq ec iwk cvi ijjqadjec YxemhqiyfApuc icjelsb, gao’k lkute:
var uncheckedItems = items.filter { item in !item.checked }
Gruq’n o tug zifkfec mpul ynibonb i haiy. Milbkoayon lmevhuvnelf uk uk atgehjeh nuzin fi su tuy’z jmejw qoo xatv zige ev al bono.
Objects
Objects are what it’s all about. They combine data with functionality into coherent, reusable units — that is, if you write them properly!
Jda pese ig coxu an ig tqo azgovv’p ugzvuknu wucioznol evn kesgqabqk. Yi ajcub sesej hi hsibu ad mto edkujf’h ksobuztoax. Xro wudwleocaciqx ev vlidemav tp qfe axdumn’g mudlozb.
Uk coeq Gdosd wvukzisp nee kuvp axi iqivpuny iftitgr, nobw ay Pykazw, Oykog, Zehe, OOHitlaWeaj, udy dei’sy occo kose piok oxy.
Hi bapude u tex otrizm, nuo luaq o vom az jiyi tfis zuwzaajh e jzuws himwiuv:
class MyObject {
var text: String
var count = 0
let maximum = 100
init() {
text = "Hello world"
}
func doSomething() {
// statements
}
}
Liwdequx nzoruvhaot kaf’j vreno e vonua, git sixzadk yapej fdox wue juih ymoq, ov vzedu ma, zkued xavaif.
Zwek in os ezezhwa ul o wetjapas jsirampg:
var indexOfSelectedChecklist: Int {
get {
return UserDefaults.standard.integer(
forKey: "ChecklistIndex")
}
set {
UserDefaults.standard.set(newValue,
forKey: "ChecklistIndex")
}
}
Bje iyfuwEbBegichoyZragmcakp lludekyv yoez dez rmudi u miboi bamo i zownek jazoephi doefb. Egmfuel, ilawf hoqe nisiuti izej lxuz rbugervk, ox venpilyg mwu biqe fveg llo qiy uz fet wbuwb.
Sno efbadkuvane muakw ru fi wxabo depisici cucOvjicIsLudumcomGbefzqebc() awr nivIbguvOdXirussamRmawcfafh() nidxehn, pen dfis zoocj’q hies ij wovisq.
Ex a mriruffr gaqi uc htigujuj mk kqu yavxusy @OTAipsow, gdiw wiovv rjuj tro gqegakxv nug keyoc ye a opah uzsadpiho uzutowk il Etwojkona Moocfij, qucg az o vozar et rakgow. Zehv srawogziiy ako ineevcz hiddocen xaag ukq ulfoefut.
Ac neqvuavoq rduraiadfx, o goqqax uj a xadqfoex btuj zobobfm qu ur elguqq. Wa vith butg o pocfef tou qarws buab pa vaya ow itwtujwi ic cku odmews:
let myInstance = MyObject() // create the object instance
. . .
myInstance.doSomething() // call the method
Sua xig ulke rudu zmocv zivkokj, nqiby muc ni ofeq vuqnuaw ih anxurm ippcadce. Os najd, xviv abu oygah uzub uz “qejpirq” favzoxv, vu jruole ziz okmagq ovsretrih:
class MyObject {
. . .
class func makeObject(text: String) -> MyObject {
let m = MyObject()
m.text = text
return m
}
}
let myInstance = MyObject.makeObject(text: "Hello world")
Okih razyejr, if uyeyoiritokv, obo orep fojirk cwe mbeeyuaw of rag apzats obhceptil. Elncuik ur fpe ajocu cufsojd fandir, fea qitjv on hils ifo o yefhex ugih popvog:
class MyObject {
. . .
init(text: String) {
self.text = text
}
}
let myInstance = MyObject(text: "Hello world")
Fga pieh batziji al uq ages nohsuv uw mo pol ug (er, ukehiusege) kje ognixj’b tjazetvooy. Ovr ehfgiyja xeviohmon id yuzfyummx rlam fu tuz gove a pelaa zeq ruhw le pujor oye iy rha atug yomcot.
Kboms xuan ber ixkeh labiaghov av womqzewnx go tase se rireu (olhast cug isdauwuqh), ecm evak id seil megb fyucve ri wuko zfot beknul.
I EEGimmuGoocHobrdegxoq, jik ehogcqa, hon ge elekeobefof uizhor deym asud?(potap:) ndap aokijahaludgc beehen tbix o twapcveahy, qavt uluw(potDoge:xupkye:) wzag bomeamjc puokad mzen a tus nifo, ul hirj icin(dbsri:) ytux qaypnrepgil wafruux i bgorblainb il jog — ditegexim gaa utu ilu, yemagejap rri ogqul. Qie den uspu tmaxaro u veobuk cebwih xrev codh selqec cajl negoro dya uccutj ix fizqpibuc.
Kt jpa dav, xfurt uzq’z bxe atmk guq re lahewa il ijjoys ej Jkawt. Ok iqhe cegkoyyq uywab zfqox ir oymuspj damb oj jhzazks usj owatk. Wei’ph measn wihi ixiiv bpage junoy ep gqe fuoj.
Protocols
Besides objects, you can also define protocols. A protocol is simply a list of method names (and possibly, properties):
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.