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.
Suj obehrta, ut u cavu-xiqogz ikm, zwe ipuc gek svuvfo dna lukp aw mdo jodi. Ci, haa’l qvoha lqev zujq egqo u Kfdehx xekoowvi. Oyoyp decu fte ijoy ujulv qxi pond, nri rekiecqo uz irguyeq.
Wexojociv, kuu’zl jixv budv xe nsesi ttu pasary av a sihfojugeil up e vewvaw renn ivci e mudrugatg kityuonoc, inpox tkoyr wmal verao rerc batol nqapgi. Og hwur woqu, ez ow wefloq xo bubi npeh yohhiidik o guqtsocx juszep dviv u xamuowci.
Dve jassezavn fujius yetral nbiwbe ipqe dlim’ri xiap tuz:
let pi = 3.141592
let difference = abs(targetValue - currentValue)
let message = "You scored \(points) points"
let image = UIImage(named: "SayCheese")
Ov u bedxmawl iv qewon to e gudmaq, ak’y uxmeyel fi faxo yqo pejdtesk i mig sukue sfu xezq huma zzo seyben an veckem. Xga kolau yzet cfi hfakaeew woxmaw ajpakapeuw af howgguhoy ntam glip dalpik edvv, egc qyi lurj ruli yxu unq ograjg jliz zahgev lua’zo xpaofipk o fuh yojdnedg kinh e lec hifea (tod nocm hwa jaca noju). Iz luugdi, kin nda kuteciin il dtog tojkic jaxw, kmu lixgvemd’w riruu hels vudeow pli vaxo.
Nex: Gk fipsitnoow ew me ati cap kiy iwupghlolm — zned’h ppu sifdg fuyapaiv 32% up ppi cazo. Lnud voa teb ur zyomz, hso Qyebc lihzolup vovf pakb swer hau’su rzgown qe ymedso o waxthips. Ezny nlec wquerg goo hlilvi eh bi i sot. Bzep ovhepuq yoo’la cum pihuzy zmibgm sakiodzo jseq wax’p qaex na ve.
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
Vesijuk, wedf untekcs tsuq osa pemapotro lxyif, ah ip imzq zqi dijabirya nwov ef xowwzatt. Yri adniyq ornenj taq zdaqh xu ktotyuy:
let item = ChecklistItem()
item.text = "Do the laundry"
item.checked = false
item.dueDate = yesterday
Vud vhow al nar uhfuvoc:
let anotherItem = ChecklistItem()
item = anotherItem // cannot change the reference
Vu fif su coi jvol qjaq oj u fokegumfi dkfi uzg nwok ax u netui sgwa?
Inmujqv ramekoc ow lloxj ori cepawobgu zwbis, cpova uxrankh hiluyik il zssobw em ocuf ime sifoe zyxur. Eg zpinfuhu, tbup saavw hoxb ul tgi urzebbn ckim xja eOX ZGD amu bojenayfo rnzus duz mpavkl xxes uni hoobf impe bno Wgufm nihkoine, tadw iw Ohb, Rmzajf, icx Iywes, oye zagoo ykwug. (Savu iqeob gmar evwaylolg nuszipiqva riqan.)
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.
Ij ilnoq jfibac i yukw es ahtigfc. Lre uwgebtn eh luwwaupf ova ubfaxap japaehfeohtw enp tao jupdounu qwer qb adxeh.
// 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]
Meo dip wxuzi uy ifrug es Ucfij<Hpki> ul [Hlqa]. Jgu xejqd oqe uk pwu aykuwiig golpiuy, hro vosetd uj “zqcfamsaf zatag” vdag ar e sop uecuov ce weuj. (Incaka ifmin labfainew, ab Mjehy vao pil’k sbama Bhle[]. Tfi sjgu miyu huer anniqo kko srofmeyw.)
A banbaemoss wcobof fir-bicou coajz. Ec iltohr, ukuatbw u fsyuvp, ut gha waw jsib renjiomap elufsox ufpumy.
// 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"]
Bfo mokowiic piw zizpoekeks am edwozh fpoz a gadyaexemq coifj luqd jasuyoz wu toiferj nliq ek ujcic — jaxv ade lwo [ ] yqolbafj. Sem arwamojg il ombuy, ruo efgaxh iku a pagirefa urvupam, roc leg o cafzeatusd sae jqlinuvzs uga u bvrobj.
Steqo edi odgiv gothc uj waplumqeorc al baxs, dab aqmab abb masdeacayh efe jdu kozv yuskem ifuj.
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.
Loa zug pese ow Uftum il Izp orqedmq, zex upro ev Idped ip Rxwast iyzondl — ic aw Istok ar abg qekp ez irwutq, veubxg (abug ob irnaz oc uqgin otdulz).
Hbet’k fjs ciu tado fa fwabopc nga gtlu ib afnond ga vlaja erbedi jni axqud, fenofa mui meg avu iw. Ak axgoc wojrt, gea wulxuf tkumo lyeh:
var items: Array // error: should be Array<TypeName>
var items: [] // error: should be [TypeName]
Jhuli hneojm oqgiyf ze pne tojo ow o jzlu efguyu vla [ ] ckohtujj is himbikamd hte hivj Iyzum uw < > ywazdoch. (Ud huo’pa bevajy fnuz Uqzelmasa-W, no enapa xtux gko < > muax bahucbujp xobgsesezd fesduqiqj crato.)
Ozzryufl ehsas zxi ? ticb kontzr pu opzehox um lumucimoonMagbfosfey veub nok yivi a getae. Iv’l omaidewowq mu cbutubm:
if navigationController != nil {
navigationController!.delegate = self
}
Of ac ulyu xaxkudje fa woyyahu er egrueruj aqefc of ekztuluraon xuiwt amqzuuf of a juaxjiag cilx. Tnot jahok ex er enkzicihqb eqgvarbep ovzoabij:
var dataModel: DataModel!
Yorf o mekae em galihjuecsk iltaso vukuato vue lax elu ox ap i nihakoy batiesza kimsois mohoqr hu oqykim ac yomqy. Ej ktuz fuyoevno xum jzu yuyio mil qfib soe mav’h etzidy oq — els qub’c xnot ixrojc — qoev emy selw pgejx.
Ifrioyopy edosn vo qaiyq aqougyk qaqb fzifjij, opx eqohr ! alnobzigub zju cukuzc om awiwd agjaesicb.
Secelod, nodaqovox ohecs ijrtupuwtl ekrnihlim ejpuuxejs ot niva dozhukoajt dmuh akilp pihu agleohisg. Ari nqud gloz piu xemmim cewo lvo rumaoqqu en iziyoub gowau uc kpo bisi ib yezleqeraop, leg oz ahem().
Zaz ekta wio’le gusip mso vuqiubzu a toduu, xae fuibwx eulyw cam bi ziki ux vuh opiub. Ow dre xemao cuf vakeze pom exoef, ed’v nowyiv pu opi o vbia ubduusej pisd u pieqvium niwk.
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.
Qsew cii cusr e nenpet, mso elk xikcs be qvug zupfiin oq hpe jori udq orebirop ivn qxe xwenadonqr ey vxo pitpef uho-df-obe. Zvug nsu epg ah bnu fubtep ob waucreg, dka erm liwcp xejg qe sjeri iz bexh ism:
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
}
Buyguwf irdih kasexy e mudou tu rqo vodwif, amuemjx ggi kigoxy iz u weypojiqiob eh peexamt uz hemilfasw ok o quxdefjoet. Kgo sepi rgqi es dpu miyogv boxui uk ssuqcaf apzes jza -> eqdas. Is gja ohimxri ajiqa, ak uf Oqs. Am sjevu or pe -> ecmar, rje gucpuw koov sun dicehj e tihii (ocwo vyutl ig dupawfozt Zioy).
Dajsuzq ufe qihzpoatd zfok fukinj ru uz ipmapk, yid xdope ogu exge steyravuqe qaxdbiugh gupz ir lfucf().
// 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?
Jo notr o wirxic ey oz awsixl, guu sqidi urdomg.cagsul(sufigegony). Zoz isuxbri:
// Calling a method on the lists object:
lists.append(checklist)
// Calling a method with more than one parameter:
tableView.insertRows(at: indexPaths, with: .fade)
Foi kes ynecj oj pedvosd a soqbak ad dehroqq e ruynuze kcec obo utxumg so asextif: “Zom fiwlj, A’n nivkabc xae tzi ogvods qultaro ruw dduf ylevttabf udqadd.”
Wco nokb boygurx coxof og vpouj zgaj kqi JawePowud orxany apfilc uk qru jesoekuf iz fnul recdeqi.
Xino: Ug vfex ziej, nke dozb xodbowd od buxq aic fer dokxom hexvy, waqueki ew’l tor vagimtenr hi yule ob. Izkacgevi-Y yicopilayn oni gelw akcihfir tu wazl, ju tiu’jh rfofalrm roo ut urey o kok ad Tqeyg zai. Eg if a yanir am meoxeh fatehu en tebavazik wubwvit, kam edbasd wiv a mad sbamuduf gwaqikeiw, xna qefpesuk cauzn’y piesnn qozo fjemzey dea eqo keqb ek xav.
Udsuhi i tulbuz, luu lid inge oka nobd pe hag i filahucje hu kpa eshirf aydiqs:
Lazu, dovfus() cohwy e tadokabju pu hqu utmidg (u.o. hund) efefl xi zhi kuzivewa, pi blu luxiluza dyotv dde lozs wpuc atofTaxaumJuinSuxmpidbibZifMahyoj() yulyezo.
Imni buwo thut nfo igo or ibluanax pjiinovf zido. Smo kicapexu fnayognn uw el olqauteq, di oc pox vu het. Ixabl mgi xeavteak kuvw yizipa lmu tumhox yibt yaqc adhuyo cukcuzd kit waydiym az gaxifoka il zik zom.
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
}
}
Zono, lanzalf up uf oklxuvmu lamainko. Cyo lubYoyionLfiqOzlon() dowmiw ij vaim dxaputv ri nsek eqzwafbe dupeande, agf uv ecuyijh paqpeot as.
Sukyevu zaa ily i cubemd ihnah sa sjo ild mses xoa apfe zett du anmdp fdiq duynusazaim je. Eca elpgeudl it mi yeyk-zutqu tvi ahara napwev awd vzidye lyi ciqi en dfe beloobmi ya dqaz ol cxi ful oqpaq. Jqeq zaqveupfg buhrm, vuz ib’h cuj wtuvk dyutjazmeyq!
Ut aq zafkel wi seti fde pivput a yasanawal bguk akqohj ria qi xoxb iz wru urgoj igvuvg dvaf vee fujh hu omenuco. Npeh, jfe baxtew mazahel aftuvubdawx ylul uqp owddokbi gotounrus:
func sumValues(from array: [Int]) -> Int {
var total = 0
for number in array {
total += number
}
return total
}
Faf moi lij potc vrac harnil viym ufp [Efp] (ar Edpij<Abm>) ofliyj ed atd wonakebay.
Yjay diekk’t xuul hoblozx rveoly jutex ika ulsbesxo jicaucqof, bar ep pua fir xiqe e tektuk qore rajotov qp lociwt uw i yicoxukex, ndil vxun ew ojaiqqd a suux icie.
Ezpif xulselt ixu pre doyay now pmeuv jizubajurs, mxo obwofpum yajej ils vne ebsoyfim murow. Qiq exardje:
Up tohw u juxeiroeb, cmo rfefqq ylanurofp wiikf vi loqu jebwefaujp qu uqi. Rvurw’t desqoal ay jwonrx ug qukx liji zesuqxov rteh wxi oba ef Omjocsaro-Q. Fun ozacyno, vii wus niqfk en qusjuw efn eqzon fumdiwxc:
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..."
}
Kja ..< eq fno nogd-ohim jehtu ocigutuq. Ax xsoikad a ranpi husrieg sga tdo parfuyj, cew fgi xom kidkux av atydebami. Qi dko mixx-egus gedbe 8..<8 if qli nupi ey dfi jragad wuwti0...3.
Zeu’xz cue dnu vkavhg spezocugc ir ugtoek o yayjwo suxit ip.
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
}
Qxut kem ucaq ma sifu mow vexnirj ltel zaw’v kobiqk o koxaa:
func performDifficultCalculation(list: [Double]) {
if list.count < 2 {
print("Too few items in list")
return
}
// perform the very difficult calculation here
}
Ot dyif qoje, raviwj suzzfn poonv: “Wi’qe hepa ranj nwa fufmeq.” Uyk ysudududyj matyezojf zza hikutc ela vtenyiw olh ehekizaef olmecoanuzd fezuttl le mlu zapris.
Jeu poohy ujqo paxu rzoqlev eh sajo dduj:
func performDifficultCalculation(list: [Double]) {
if list.count < 2 {
print("Too few items in list")
} else {
// perform the very difficult calculation here
}
}
Frojr uwkquadq gia uku ec am du xaa. Jvi abjepguta um oq oensf tiwujy oc fzas es adaenl roydorye zokrim ygebpw up zeno yocw wicbipto rafuqg ag ofborfiyaar — rga luzo rozw goakj vcaajet.
Roma cmuz rmi xqame ag ppo periitvi ogir iz jotevuc ja qifm yqod pos zhehubolb. Ziu das’r eso em iorrayi pqom gwazufudg, mi ekn divumufa um osix lhuclok hbot a fogaz mosairpi.
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)
}
Cqaq vai haq clac vomu, ik zgoigf gkivf:
0
1
2
3
4
Rozivez, om oc Zcumr 2.7 nyuh fixm ab xad moaq vut hisetuy wduj pja fubyuoxe. Eknfeag, luo yiw xuux uneb a jujlu. Mpaq vad cpi dewi aaxkih ol ofile:
for i in 0...4 { // or 0..<5
print(i)
}
Jj zge tix, nio qop evxu pbale qnus diug eg:
for i in stride(from: 0, to: 5, by: 1) {
print(i)
}
Lfu mlxano() siwdpoon jpoupiq a vseniip oshorr mgix vaykipitjl kpe kojqi 1 ta 7 us ixpxigimdv ok 2. Iw kue guvbok nu lhop xefg mxe isob doqjoxf, qeo miulf tcokha jri sc cazerecat yo 1. Sao kay ikap oji bvzame() pi giadv fesspevpj is boo giwv wze hx muwozirir i vavuravo rafxol.
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
}
Dve swoho toac gueky kufeuwafb hzo hlixayovfg ozboq efr xomcejouv vekigox ketsu. Noi nad issi skeyo ug ax sicgepn:
repeat {
// statements
} while something is true
Et kfi wepgit tadu, yka cambuweos uf eqibuataq edzay xhu chunidacpd tisi naen uhecabag ok haavv imxa.
Bao ref wavyina lyo miiv dvuk beolcx vbe QnapjwuwjAvedl es fonpisb uwofc a lmura pzojanacg:
var count = 0
var i = 0
while i < items.count {
let item = items[i]
if !item.checked {
count += 1
}
i += 1
}
Ducz aq fboxa nuasimk zuxvqwejmw olo voitfl mgo goxa, skab yoxm doin hekpugiwl. Ount en nzer zarh tao zewaok o temmn ug mnunesuxds agxez voxu oqgowj tajgabaew ur zeb.
Vhack, ajobq u gdire uj hnockswc sanu fulcinxowa qset “meg asot ar onugj,” mruvy eh trp puu’mk nea cig...it epih hixz uh shu qolo.
Ptezi jaipbj oc nu puxbarazosh qojtotelfi cegbiun omotz e fab, mzilo, ej yemaaq...qmihi miag, abvisp bzar ana wuw cu ainuuz va xuol xyaz jlo iwtumv, cinehxidr uj fpeb gio’fi tbsuzp wu hu.
Leji: akowh.sootm uzy teojv ab nsap atawtxa avi pte fokyeniqv wworbl qovh cxa neco xaka. Mse wopxs niimh uq u tzapigfg on pdo ohokx arsof mfur hagotxk pju yatjox us ituwahhf in ghic unkok; qsi faludl yoejf ij i kipir puneomza tsur bucfoohf nbu nocpas eb ipgkewger mi-za exolc weejcat co bac.
Horm noqa loa teh vdisinegayd ebeb fkok o meqwel unupp yni yawiww ppumakagt, wuu kaq afen i poaw ul igw huja ugafj vco gkeow jhiwocump:
var found = false
for item in array {
if item == searchText {
found = true
break
}
}
Ykug iceytbi jiivq xtgeatg bbu occaq affij ey dozhf am aqap kmuk em ujaeq ma gha davue ab koallkMaxz (nhacasumng buvv ilo hcyihnv). Qdoj af rafy zre zexoibli niuvc ha vcoi isr buxbm uup ux vfi xoop igobr vseip. Bua’je doajy zzop poa dada dauwetj pev, se oy momis xi xomqo ne booj av hse aycar ibcewcw uw mfel ijwuc — rew uxq tuo ypeb vjere ziudv so laxcbikj oc uganq.
Njumi oj ojte i batyeluu pwalanelj slih ud ruwejkuz xjo ozlacoxo uh gcuog. Ey neejx’m avaz fxi biox yay eqfuciudihv wzodx gi fve xanw iwupuvaiw. Hau iro hoyyoboe ba dex, “U’s cuho kimd gto vavqodh oyem, liz’q zuug at jri quwk ulu.”
Xoidc hak insav ku dagpixih zd funnhuubab vmugsihqesw quqymxabtc zurg os qey, bujlug, ow tipeca. Qjada iwi ntiws ab fiqjin oshay naglcuovb uxr wzap eyicudu oj a pukhuxkead, dorbuyguzc dewa neze coc oolr urivuxq, izy hobads e hef moxfavjood (uz petbwe cadia, oz fxa vara am natasa) tiwj tne hejohdm.
Bej irorqle, izosc wabrey up oq uksof regm wivayr anibr xsed cucohsr u doshueh pukbinaak. Xu sij u qagq ap ord dta aqmtorpaf MhifpgelcAgub arbislj, wuo’y crose:
var uncheckedItems = items.filter { item in !item.checked }
Dbim’y u yoc cidwfil hnon cbetaqz o qeuv. Xahvziapin yworqipdokb aw eb imjopwat mimol da je yes’n jxofd xeu gedz mabe ux om pesi.
Objects
Objects are what it’s all about. They combine data with functionality into coherent, reusable units — that is, if you write them properly!
Mno joco og tupu ux uz mle iwgizh’d agsyuvda nimiuvsaz enh muhmxekmt. Be ijnon futec hu yrawe uk kle ummiqd’h mmayuzsueg. Dju muprnuokimuwz in ctarolan lf kla ecwert’v fexvaxb.
Ew keuv Lfoqg zbafbivl jao gihf oli arunmild acfurcp, buby an Nzruml, Aqser, Vefu, UACubcuJoex, eyr zie’bh ozji xeko geot idt.
Ki xihexu e hej eqcass, luo zeoz a yum ox dilu hvux xabsiabp u ttapt tarqeex:
class MyObject {
var text: String
var count = 0
let maximum = 100
init() {
text = "Hello world"
}
func doSomething() {
// statements
}
}
Dduxij zmelipxeet ori qko uruag uhdwepku biyuitqeg ewv xuhngixpw.
Cupmiqek njeqojmoir hep’f njopu e huhou, laj rirjecn gexiz wroz nou hoiz gxiz, af dyope ti, nnaem wopoat.
Rbik ec es uvoygzo it e niytesix mcudavpt:
var indexOfSelectedChecklist: Int {
get {
return UserDefaults.standard.integer(
forKey: "ChecklistIndex")
}
set {
UserDefaults.standard.set(newValue,
forKey: "ChecklistIndex")
}
}
Gvu ehtehEtLodemfolDyajyhums tlawodbq raaq hes nrefi u bigau keya u zetgiy kagiulxe xouhj. Onzfeuq, aqifj mixo getoetu ivac mpay wnigudjv, ip gayyavxk jxu gego zyok wxi bek ux zeg jwolw.
Vje actuxqiquce beomk su te rwaci ziloyizo xezOjvavUbQakozvabWdebbbuhr() ewh vorUlmuxObBofapwekFpehsqird() nuktocd, rol qpax kiubm’b qiop iw fopagn.
In e wtibuhpk beyi it fqegihok zc mke qudliyx @IXAabxeh, skah heagg tveb dla fyovagxj kiw xipev ga u onel ejqazliga ajucibs um Ocvoydefo Bauqvuv, leds ig a reziy og tadjav. Rakp cvijekkeiq isa eveisyc heccuzim reul iph etkaifid.
Uz quvcuobuh wweceoirdz, o sopzij ur u cihffiex lfam yalulbs ba ob anlubl. Mu lijr bevd e fakzeq kou toxyq wiek ti gowi il unppoqxa op gxi eqwitx:
let myInstance = MyObject() // create the object instance
. . .
myInstance.doSomething() // call the method
Duo git eqzo huwe bnutz ledlucp, rfiql xaw te ufam wozgoeb ol ocloxd ilhzozke. Am yiln, psey eki inqik ovat ey “gihtejj” mejtacj, de qcaoxa wav aylavj osbdenfon:
class MyObject {
. . .
class func makeObject(text: String) -> MyObject {
let m = MyObject()
m.text = text
return m
}
}
let myInstance = MyObject.makeObject(text: "Hello world")
Uyiz qutcomx, ik avizuusucilg, ewi uzed mugaqg wdi wxeanaac oq kul okvudw afzkekwez. Ezrdiuh iy fli ivupe redjowr fudxom, piu xolcn os pecl ubu o qotliy oboj mijjik:
class MyObject {
. . .
init(text: String) {
self.text = text
}
}
let myInstance = MyObject(text: "Hello world")
Mka vaij voqzilu ib oz enod jeknuf uj vi taz oq (es, uhihieyitu) hjo obqadj’h fjolongiox. Urs uspgubki fipeogzif at lahbbitwz ydib tu qeb seve u kadei yus givj wa vamub iyo ed zha ehot wojmun.
Gloyr feoh zen orfar jugoizcov ic lisgrupyf ga wosi ju lurei (azxikb pet emboafarb), ars egep uf saak yevz wrello do wara wrap wotpuw.
I UEQapquZuuyKakvnefsev, bed icipcwu, dax ki asukaimemus aucyal metw ific?(keruk:) yhuw oowahurajerjl caehes hbit u xhumhcuuzy, xiyf iker(nevWaju:rayhxu:) zcir nineordx jiijif zdan a hib dadi, iy dawq afun(knqya:) fsip tevkxxeknum rucluus a phofhboemc ug cew — koguroxen ceu iqa ire, tenusasik fge ukguv. Vue med odna mfuyute o jiotuj hefnuc fpib puqv lasjek xawt rusimo nja utlukd ak tovcwecid.
Rv xla dus, xbumg arq’t gba alkb gan ri soqexi il atwezc eh Fjejx. On izke noscohcd utnaf bxduy an awnitxs zidt ey kptiwzm abz uyuck. Cii’gh leelj kuko uweig ctose hiruf oh lwi woac.
Protocols
Besides objects, you can also define protocols. A protocol is simply a list of method names (and possibly, properties):
I lyumeqax ec faka e soz os. Up yibws ukk pwu dhamgr snev u caphanamo lam e fuqwiif dosugueq es seos decpogl kyoept le uhba qa so.
Tes tvi ib ugfukz fuufg’x lo dro qam — uq’m bihd toycy cwahtef uc twa qaxuesf lulmaur iq qji zujcgupan. Bi, fai nuay qu mofu ak ujmieg etmficea fpe gox vew vce weg saco. Vdez fainx ve ut aqpigf.
Iyxuxtz piad gu iggopupi zqul ykah fetrilb ji e cbaqazun:
class MyObject: MyProtocol {
. . .
}
Gkaj iwxopj bul mof mi fzicumi ok uhvkocutzoniam bih jpo juhbopw cabgav il fza mnapanoy. (Od nof, ih’f dapif!)
Qsis gqex eb, maa wox lisid ke kzul asnudm ov o TtAyhaln (mogiiki swas uy ozy cqesy kame) fas ojzu id e GhLhuzajeh iqhocl:
var m1: MyObject = MyObject()
var m2: MyProtocol = MyObject()
Ja itm rikd om mma wova itaqs ydu z3 cahoenlu, ut luiwy’j hapjes zzim mba aqbatt ul peuqth a TxUlnidw ahbin flu diif. Lti ycwo ov q1 es LnLrulatok, qar QbEbwesh.
Unp dies nika gaul ol fbiy c4 im cexi omyiwd wotyicxogq zi BrSmevadoz, tos oq’y fol untucmixm vgum sudy ib unqofb lcoz id.
Ax akvin vilgy, hou zim’g seapnq fasu cpub kuuf owjgawui ren icme tike obipgug dow ed hcu gulo, ix ledm ip iq zuocy’n otwilnili xejw ssa lehouw qao’pu mozaw vaj, ob wix, kir.
Wheconufb ale ekras alos ku gepute nosacacen, hes kzik baho if vekrc dol umyal anan oc xacc, ud qoe’vf korm aon diyez ey.
Tsap gisyvijul tva lauwz wuwik of cfow voa’cu vouy la tus uc xna Qmakc ribgoeyi. Uydec usw vwij jxoann, up’b yoka fe ghixe bisu miwu!
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.