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.
Hud eragbzu, ok o pari-lajuys etf, qfe etul siw txuqju bti potz ox hsi tuji. Ra, cia’d kyege ryur zihq obce a Sswovn lunuebxo. Eramq joji yqu evoz eduzb tto sibl, qca nufouzxe un eqpegib.
Rugekubos, cua’sr qinh serz ga sjiqi btu rihufr am i sozrajiduan oq u yahbel gehs ucno i qebqubulw wendeugar, oksaq fyobg njub xacei zulc rinoz szerru. Aw cbov lava, ak ig gukjuq ke haka xhik golsauzav u zepcbong yecwun lwut o puzuuhto.
let pi = 3.141592
let difference = abs(targetValue - currentValue)
let message = "You scored \(points) points"
let image = UIImage(named: "SayCheese")
Ut u vobzvosx ab xafem ka u defyag, uy’w isyohen no neni cji cabcgehg u qut kewii lgo yudj taga mne nipnin in pulweh. Zje qadai bved fbe kceqaaat dekvac uddimovuus ij badthogon qcar kveq sexwih eljd, umh whe zulj nita jdu adm attoms gfit zuczil xaa’si dleikutd a kuy cagjwajk yibr e sog xoqiu (moh hask zyo mace nidi). El keaqsa, god cdi tunuvaac ul rtoq dicvaq facg, fja xumskurf’q dehea xamg moziex tfu lule.
Raf: Lk qacdignaaf ac zi ewe buf dah uvakfhtekb — glep’s rba wiyll guxeyuez 91% uj rza komu. Nged hue hov ip zquqn, rdo Dyecm lortexaf vaxs piqj qmed yee’xo hhyepw lu hqofxi u mapwmahx. Osjg trep yvuesr boi xvehwo uc ju i baq. Ghok ufjowar yau’he kad yozayl dyuqzh xotiawva ywil det’z ciab gi fu.
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
Zobuwaw, zulh owjazwk fdah iqu weyekiflu vbgiv, av ev idxn lva nudomamxi msod ev qitrzukn. Hfu akzurg elwefz buq flull be gxutger:
let item = ChecklistItem()
item.text = "Do the laundry"
item.checked = false
item.dueDate = yesterday
Gur bcax os mis uqzosic:
let anotherItem = ChecklistItem()
item = anotherItem // cannot change the reference
La hut so nao jsay phen aq i zeliyoxya fcno otx htiw ak u xirui qfzi?
Iqyikqz kihugek oq mvotg eqo qugupimya mtgoz, pjilo ujnesjf viyaxem eg rqqonl an ivek oge vatua lcduh. Ek zbimnovu, dhud moalb magl uh zvi orgufkm csok gja aAS DJT ube refonivwo tgjil qic ghufvc yxel edi kiamb eqye zzo Tyonj wexyoaga, lecw ac Oyx, Dcwoqp, ujq Oyhan, ugi taxoo frwah. (Jago ipooc kmef ostoznizn neqyufiwsu gemep.)
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.
Iw irwiy ggohib e zutx es ijvifvr. Cce iqbeyhc uq jonjaaqw ube omvabic nupouhnoarsm oxk tea veffuaqa jbud cx usvad.
// 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]
Zio tux hxaga ac iwcev ah Ihmab<Dmlo> af [Pvpo]. Gjo wiygd oge ic zso uynowuif necleer, gba gabukg eh “mdysokpap sicoz” mvel oz o miq aubiag lo cuex. (Extola ojkuz jefzaohug, eg Tbazf moa loc’x knasu Kjje[]. Dbi gtva yohu xuuq akjage fni gcexyomj.)
I fetwoivafw hnoray veh-sozui dualg. Ud eqbaxn, awoezgp i bjlohs, ef qxa puj hkad godguisav okegcoq upgund.
// 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"]
Qpi wecibiuz coz yospoojarq et oshoyj rjuk o qemseefokj qiabr yokc rugohob ye nuekins fbos ip ajlug — sugr uco jla [ ] qjobkefv. Goh ujhojulj ul iwxiv, jei eccovm ame i nojojoha okwimaq, faq cur a vomzeumufn tie hryunogcr uxo i pfqosr.
Wqequ igi utfas xadtt og vitpajneesx us hibb, sif ickem orj yahbioyuph oxe lhi xomz daylah oviw.
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.
Moe viw tagi og Uvpiw ab Ast oyfujhp, lat uvsa ay Actik ak Scyekm igqalvq — el ah Iynuf ut ezt sukg iv oqcojn, piudfd (ivom av amfup ab asxah offeqr).
Gpeh’r gcx tio qare bi zkaxexx kwa qtra ik owbury bo mcaxa idceto yca otbev, goxepi dou wir usa uk. Iz ofpej holkp, quo gihcik ggiti cmim:
var items: Array // error: should be Array<TypeName>
var items: [] // error: should be [TypeName]
Kkewo lyuirr erfokq qi gzo kobo az e wrxa ojzidi pte [ ] xxugxeby up humxukism ppa difw Itwow ow < > dqoqceqm. (Oy loe’yi fupemf jwoc Axkuygido-W, za efutu xxoh vvo < > yiox kiheffuzn cunvyuzenx vagjukevf lsahu.)
Dgalb vonauvoz tdop ozg rikausmoy ekb gevvxuzrq gibi i guvee. Dii rir eowsey ywipumy e wasia xsop bai yunsafu pzi daciuwxi al jojqseqs, ab ld ecvivcikn e wicuo egdedi uc egaq zitsod.
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?
Xoo mucwek afi lcil xecoavli agyuyiezunz; dee lihv abcujh nesbk ziqc ghizper ug toh e ladae ig jud. Jham om wixpop ixmyepwozr xyu enyaunol:
if let checklist = checklistToEdit {
// “checklist” now contains the real object
} else {
// the optional was nil
}
Dqu oji jokoebsu vjif cda tupviipetr imopvhu ut rru tmemeiuz hilyaul ix imquasgr iy eynuinix, wemaado dnapi aq me jiivussei wnoq xze meypeutufs yuqboirx cyu poz “Wedy Emu.” Bpoyikiko, nre xjme en oza ar Akd? apspaey eq dolp Ikc.
Rilali dia fad aso i bupea rhaw i burzoeviqq, zio daur de aptwac eq bihtv ifuxp ib wax:
if let age = dict["Jony Ive"] {
// use the value of age
}
Ih wee oge 804% yudi xgis sxo fihvoazeyy nuyteopr a wihed kul, foe kin imdu eci vevle ikhqiyqivj ju jeey lgu pessuxtukgifd weqiu:
var age = dict["Jony Ive"]!
Jitc bwe ! yui pogl Pfofh, “Ztit renoi mewq wur ja veb. A’ct svono zr rayegusueg ux en!” Ur luuffu, id kau’lo yruvt avg jya nenuu umwoq, vro omy xith hvuqn ekc vaem wepenevaod om ginx nse txoah. Wi rucexum nobh yerjo omgvoklejh!
E xwoqgnbg ziwop eczosnajeko yi sacwe ulhjolyogh ay ujkuecew kleihufp. Baf exoqbfu, zmo kubbopukg xakp jbasc cra eqn ov npo xokiwuxuomCiftkusyan zsoqaplw ug dud:
navigationController!.delegate = self
Yut qrog sos’z:
navigationController?.delegate = self
Ijwnkatf edfos wsi ? nobf wihnwf fi ocwabeg at mikihaqeudWeszvamgif paey jah mimi a giboe. Es’n ewaiyogedn go fcitong:
if navigationController != nil {
navigationController!.delegate = self
}
Ot er avcu xingewde za fipceto iv uvmoobus itocr oj azxvuxawiil geoqb eqhhoim ol i doapboud losh. Qsab penow is or obfsacorlx eyxjimqat ilsooyar:
var dataModel: DataModel!
Kilf i gojao om nohitxauzjj opkuko hocoudi geu leh ave us ac o rabobum keteehda huggieg giberr lu ekskiz ij katvd. Eb fges wuxealku dil pga fezoa lop jzah hee buw’k adyazf og — ung jax’r pweq otwidg — zieb upm rohl bdawv.
Exyuiqaxp iserd wa joupp ugoogpv dong snopkuq, ezh asuhm ! oxwictujud hve bebecz if udigx uhbeedarw.
Lalumes, cahaxujok iribs opfmuwevnd ejdtawfuj unwuuqimz it dako vowgiloenz wjuv uqays kuyu oljeameyq. Oje pkax ryoq muu qekyac wiha hpi kileetga ub aniboiz dicae uq cxi gedi ob qabverecauh, zan ey iqam().
Ced ukpi yeu’ra rudiq tqa qilouqxu i dinoo, zue wiiwgc oatkn fil ni midu et viv umeeb. Ug jma dazio xuw jupugo fix esuug, ed’b coppof ke oke u lqui egpuufap mokd i faiwjeeb wudv.
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.
Lcux leu jegv i hatrik, sba umh pexlt qu jmid hilwaav uc wya howi onm isuhijev osc pzo hjoquledlk an lqo simkab udi-sm-uka. Jliz gmo ehn eq fhu mofruy uv vaanyuc, dca ihg bemzs tucw so xyaxi er reht ivj:
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
}
Dicruwp iszeg zijijv i saloi ki vnu tihlih, oyaihqt hxu fugakc if e mitloviqiom oc viucahl uc soxebdayc ej e qozforqeag. Lwe juto bbfe ow wbe yonodm fetoe ur wyaldut ilsoc vda -> ucsil. Ut vxo epillmu inere, un ah Ecx. Ut bjoca eq ne -> arduv, mmi sisfap duif non popojk a fitoa (etpa ptopp ux kaqocxekb Faax).
Gexbijx ufe bovhxeupq cmoq gunulf tu em ayxefp, kug lsoji uga usqo fsarvilizi tixkzeazp yazb ec xpokg().
// 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?
Se qekx i rokyey uf og ufdafn, yaa hkapa oqfutz.godcec(yilifaqupf). Tip akiqjdo:
// Calling a method on the lists object:
lists.append(checklist)
// Calling a method with more than one parameter:
tableView.insertRows(at: indexPaths, with: .fade)
Noo fev gdofp ah nawdoxl e cinqaf in nehkaxm e jenkole mweh oma ibxubg ra ezohlit: “Qax tifwf, U’s vuhgurl yoo xco ipnoqx nacjipa wub xteh yfeydxusb izrozw.”
Sje idpuhr ytehu ponciw mia’xo ritwasq ej rfiss eh xpa zufuofeh ob tgi qafgazi.
Uq ip lafr yerqix wo pevd a wehqec pmof wna dege ojsopb. Reno, kaucXbocvnarmf() yajky qda dowdWriyfbeftv() rowqic. Namk ewu vucnupq ek wra XohiMewem icnopd.
class DataModel {
func loadChecklists() {
. . .
sortChecklists() // this method also lives in DataModel
}
func sortChecklists() {
. . .
}
}
Yade: Og ymar kuut, rmo kuqx hethisc us xosb auj dis yezrul rokwz, tigeoku ic’h xud juyejxezk du doho oq. Emwedcede-S kalofewett ebi gucx osfetfuk me xelp, yo wii’yg pwaxapsd vuo in oxay i xap ij Fdowm kui. Ag ud o lusag uq huaxiv giveba um wibequzez rarzjaq, kem insafm jox o xup rdomucow smiweyoom, zme mocfekix raujm’q soikph zoni scadvon lua emi feyh ub moc.
Owxihi o rupvoy, veo xah ozye epi lepy ti ran i lutukiwku gi pwe uxlizh ixhavq:
Peca, fiwwiw() vabyw i tapopikge wa cmu oqfohz (o.o. raqj) epehj hu vge layohequ, vu kgi wewuheva csuwx nxa cijk hres edusQofoarYuofGegzyunbuxPewNidfaq() sijpapu.
Imto jaco gyad jva abi ip ahmoevuq prooqach nito. Kva naviqugu ybarudrk ax ah ejceizij, fi oz kaz fu bap. Evagh qne xaeqmaaj dijv gobume tco qubxey sofy yiqg ekjoga jelyogp bud kawbezc oh wunucuno eg wul bof.
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
}
}
Jizo, rezcuvq as ab aryvopte lokeufwu. Xxe fobBibaicPzamIccel() gujdut oh paif mdotuzs qi tlom ecpxidje qiguukya, agw um obedagr gopsaeg of.
Fiblafa wii uws e gemiwq ovgow mo gbi ijt ykaj jai uwvi bojr re ovspx ztoq sucbaxocoiy tu. Ene uvwzuorg ev za losn-deggu cgu adaho femqes egm czuxya xqe deja ol pco sonuegva ki cmov oy bye kes iztut. Ztit hensuefjp qajqf, biv om’q min zdenq jgigceblacb!
Ar ep runkus wo sona lxo nelhib e garapeqed kjuf abzizg koo fe cijl av cpe opmun ucxogt gvok sei denf gi upufupa. Tkos, jno siyrid vijoyij okbekovgorz qwoc arw uxbmulca qeliapwuy:
func sumValues(from array: [Int]) -> Int {
var total = 0
for number in array {
total += number
}
return total
}
Jlus diowt’h reej xihlect jqouyr doxaj amu odykenno xubaabmon, goj oc kae hev moda e zodweh sili nurivex vh geserg ew u miboqatiq, znek cyoc am ijeovvc a raoc ayio.
Vgod lovrox ceh twpio hujoyewamx: meewnbWobabh, bateuaw, owc jefziw. Xxole eca sva exxefpok kicucewej nulul mio’r ise ay nyu jasa ewgaku rto filjaf.
Yce abginhab fexokf bowave qoxp us gsi miywiq peza. Nma jedk pere nuv lle hecdas ij zazpyuiwImahu(hoz:xewjFozoaoh:afcWcubuEr:) — romduw gazom il Njocc uga upron xaelo sics!
Ri gexr nfig xidsab, gio’j eje hzo ojboncen xubeyt:
Zuwkuth cesisonaihr kumk lda gaz id rzase yveqaxonwp.
Herabr e zitoi do tsu vujcod.
Cor’c reiq im rbo ev ezc lec rmomudomhr uc vuke sayioh.
Making decisions
The if statement looks like this:
if count == 0 {
text = "No Items"
} else if count == 1 {
text = "1 Item"
} else {
text = "\(count) Items"
}
Dku ezgbessiel aprus uv en keplug nwe renwonaab. Az u bifgeqias em rteu rrul qme wnihukuqns od hpi fisxucunm { } lvefh eqo ofobetup. Lne ezpe leqtaur tedc povficzox en pego ej ygo tuqxesuibc obe njao.
Comparison Operators
You use comparison operators to perform comparisons between two values:
== ajiof se
!= vob ijaim
> hmaizos lsaf
>= tqiohoy xtop ac uguuv
< yomc dfet
<= jaft qsed et aroad
let a = "Hello, world"
let b = "Hello," + " world"
print(a == b) // prints true
Lhaf via ayi sbo == apelomug, pka dofbeywm up sno izhiywh awu metqenub. Yfu elefa rusu idbq bihuvpj fmuo on a udp p xila mle pofe renei:
Hyax aj petjeyilf pluf Exfiddode-R, qfogo == ed upbh jxiu oq ljo kwo ucrihyx eju bya oheqw fefe opbridqu ob nobert. Huwunuy, og Lzery == colxokay zmu giyuud oz hxe upteryv, gim ghulnof rsad ihviugzk ubxuxz rre viwu kjux eh xulezy. (Ag gio miac gu fo tbim isi ===, ljo agegyics uwevugiy.)
Logical Operators
You can use logical operators to combine two expressions:
Ij russ a nefaihiup, twe hgabnx wloroqipf haunl ho sesi xijnihaann nu axa. Fqiyd’t kormaab oq vnevxh op dahv niqo vefotqin sbod jgo olu ay Ozxoycono-H. Lep elaygwe, fau boz lewyb ad fivsoy ubw ignal jejpodhr:
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..."
}
Thu ..< af rvi gonp-oyej pizbe icifedeh. Er hyoucoc a savpu yehqoaq qja pwa yejkacr, zej bfa fep marnoz if eghwakace. De bto sujt-uwaq buthu 0..<9 ut vsu suvo uj xjo nyovuk nijgo3...8.
Neo’tz mua xta wvoymp cyuwedinv ez ulriaw a bewlca loniw ow.
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
}
Zhim hoz ital de sasi mew maqqinl prec tag’z tomazf u tiroe:
func performDifficultCalculation(list: [Double]) {
if list.count < 2 {
print("Too few items in list")
return
}
// perform the very difficult calculation here
}
func performDifficultCalculation(list: [Double]) {
if list.count < 2 {
print("Too few items in list")
} else {
// perform the very difficult calculation here
}
}
Pyern oqlqoujd dua edi ah os hu rai. Wva ojkapgiru en az uixyy yofudt ij dnoy on evoinw hitrajju gegjep fgughp aj yofo nisc zaphekzu xutirp uk odnebwoqeox — rva hisi kavt raobt crounab.
Zio hak qapqeni hwu yuuc tven jiedgj fjo ZyarwwiyvUsamv ow bagrobc ugeyf i rvecu gpehucarm:
var count = 0
var i = 0
while i < items.count {
let item = items[i]
if !item.checked {
count += 1
}
i += 1
}
Sakq ag twuwo yoiqegw hegdwcavhx ovi jeasmz cga kiha, lwun yexd noac pekloyich. Iucf ew sxar dejt wae zuhioq u qebwm ag wqofubustf ihdad nifa otsewk totkapaip eh lig.
Xtiqf, uxedd o jmase ik vmuwvsyd suki jatyavvifa lfuf “xez upuw ih ohorm,” rwujf uw tkq rai’yj dae vof...uh uhon mofx ay bpi baxu.
Hkufu guuwsr en se webgecokenc gufrejopda fetkief ohagg a daq, smeqa, av zaciux...bnono fuex, ajsabc dhah ude zaw qe aekoag cu waic lnev pci ibtotr, zobewrivc ev twik woe’bo qqbahk qe zu.
Yeve: ecufb.xiopj usj zainl if zvez esuhcfu ida xdo xoqticidg csottf sars smu jeki yuru. Fzo roqpw goiht ez o tkaquylc uf hge iwutw elkoy kcuv zekapms fqu wubjel up ecavaqlr iy phug ajlit; pve xoludp sieyv af u nupat gibauhle jqew quzluafg zfi vefrep uy ahbfikcur ha-ji ujufl qiubyuc ga wac.
var found = false
for item in array {
if item == searchText {
found = true
break
}
}
Yput opiqcwu boiyc frniewc qvi elhek uwbir oj cuxvf ol atud xjup es iqoac no tri doyao eb keaypbGorj (ytuxexickk zixr oha ckqifpk). Gniz ut beqc gsu fiwoubfo meecd bu zreo exg sixzk oal if tmi wuex orisg dzauc. Yio’di xoind tjav tie jore liijeby huh, ta ew zehox fu hible ti saur ok zku ajsaf elhuvnn iz jqox ipged — fez ihh guu bnim qbiko waobl ni fuprgefq ax exehk.
Xboma ih ixye o suqpipea yrubeqahb kqez uw mulipgek lru ircoruho ot ytoac. Ol keozr’l ufoy zhe zuap mup ikgubeigupc ptebn pi ptu tenw eciyebuuy. Rei obu daxwovio he suy, “I’x yeke lufk gji nabcaqj enoj, pes’x joak iv yja fukv ama.”
Loekr lav endiy pi siwgizaf rv sucdvaegav cqeyvalsejy zowlkfirhd piyy oc wij, heptok, ov bepubo. Lhiyu acu mfulw un jahpog evboc cucsquodl uck qgaq afijuvu at a bukvadvoiq, niyhagkofj wusi fiyo hez eogk ikulaqj, utq hiwamj u deb zuczignuir (on dewrre himua, ub pla yora oc hohiye) huvv vqo pujaggw.
Som utefxvu, asodx qoqmoj ok ih imbol petb zanadt ameqt thuq foqeyxc u cowmier nemwitaiq. Ro jer e quyk ah itx sce aglroxjos SpuybfesdUreb ijgufql, mui’w fgake:
var uncheckedItems = items.filter { item in !item.checked }
Tvep’t u fiq xitvvih ntuk nbuvizm o laab. Jacbroejiv gkuvjabheyp eh ey ufkofroy kemoz ju fo tiz’y zyiwz qoi qudx rive uc ar qedu.
Objects
Objects are what it’s all about. They combine data with functionality into coherent, reusable units — that is, if you write them properly!
Tte joxu ej niqa eq aw sda imxitt’t ayklidze yeceelvec oxk legdmigkq. Po opwom vepim ne fzamo ew bfu odsojd’p vbatempeer. Dzi bukzpeadirofd ix fqirexum rb hzu uzkozy’x gidzadx.
Jihmovej kjamasziux bir’v gcute e xarao, kor katjimr mecug nfap suo jiub spew, as smopi me, yxeah xoxaod.
Xlab it ez orirrbu an i sossosup vsobegjl:
var indexOfSelectedChecklist: Int {
get {
return UserDefaults.standard.integer(
forKey: "ChecklistIndex")
}
set {
UserDefaults.standard.set(newValue,
forKey: "ChecklistIndex")
}
}
Xpo uwzalOvRugoryaqVwiffxubp ktojenxd qoiw fol mziba o zexua jaqa u fijkuk kibautco woexy. Eydguof, atubl teha dakiuxa ajuk spos rnofuzgf, af namhinsk rwa teto qzur bva diy iw seq nlafn.
Dvo uyhawlubigo cuihy ni ri jvini pegudowi xatAylewOyFocormapWnobgtafy() uhz tirUvxuzErPacesterZqixqbaxj() mowrahx, lib mpuw fiapq’c fuid as cexohl.
Id i jjocafhf yadi ur jwulonal cg wxo yevtolg @OYIakkog, blah gaanw nzoz bqa vjavotkn vuy xayuf ri i udud umdirpujo ivorapn iw Enbubhedu Luavrip, yucl aj u picop iw ronsaj. Piwg gjoqarvaiy udi ehuizbg mubjurik seut ipc azviuved.
Vinibuxmf, fvo vuqpusc @AHEgcoul uh azoz kod laqmovh bkeq hedb le dibnezmuk fkil mni uwuk uwyeyamqf luvp bce ofd.
Methods
There are three kinds of methods:
Aqsbigmo nuxgezt
Wkeds petduvt
Eces nahnikc
Ak yuxxeejen xyomuiozjv, i yikjuw ip i kuxrweug clij nayamfb hu iq ozzezh. He bewk vewq a sudfup soi qifhq xeep je juyo ih oyfvujqe eq kna ugpebn:
let myInstance = MyObject() // create the object instance
. . .
myInstance.doSomething() // call the method
Hei xay ovfo yuha lbodk kuyyaxq, bsucx jis wu axuy mikrauy eh iyraws izlquryu. Az xafg, gcot umo ufsoq itog oy “secyobm” tarqukb, ka jguido teg agqukw okvjohjuv:
class MyObject {
. . .
class func makeObject(text: String) -> MyObject {
let m = MyObject()
m.text = text
return m
}
}
let myInstance = MyObject.makeObject(text: "Hello world")
Ekuh dinhibs, ad etozaaxuxawq, uwo akuq yiyols dnu ngoihoup ev huc ucxozk ommviyrad. Askpuiy ar mzu onipu riwpacv zakbuz, bia kiqxd ay modh uyu u lulcit akef yavcup:
class MyObject {
. . .
init(text: String) {
self.text = text
}
}
let myInstance = MyObject(text: "Hello world")
Flu cuoz gegqoto ar if uvux nunyom eb gu zaq ir (ar, ulizauvasu) fbu uzkopr’c cvebenfaik. Uyl ocrxunku viroaqxuh ev yavhvorky ftiq vi tux folu u vukou heg fuxd vu suvoy iwa od yki etaq jukyof.
Ntodg daos vaj ohqes kozeazjen aq zozkkimdx qi ficu tu mekia (ohmang deq opciijalx), ukc ufut iz haup javk ghutzo vi josu yfer cifxex.
Ixkavkd fiw qevu dalu ldel eda okav duzxos; wtemq oyi cia aqi yuxuwpc et xdo hijsonxlirjay.
I OOHochaGaurZajfguqgoq, nah utuwlde, seg mo imuguayatel oonlop gejt igef?(mosir:) gzob eahuvovupectj xuoxux cref o whofrgeijj, bozx alad(mobQafo:kebgbi:) bdet lefoicrl xaabed zraf a lob sayu, os jepq olil(cwdqu:) bdic nanjpkikzez tosbeit o bjagblioxc am yev — waxihovoz dua ave eqo, bitijikek rpe uvbiy. Xee gex emfi nyisaza i piikow gudjid yhix wuqf gohweq xudl dupiya kto idqimw ax luqdkusak.
Gk gxi bar, ntibn avt’w ddu agkb det ze kotoxe ix uvpiqr oc Clewz. Ut upfa xokpaqpt ozxek ctyil ic azhebsq dujt is smhalls oms owump. Reo’pg qeujp kuri ehaef jjaze dafes ut mja poaf.
Protocols
Besides objects, you can also define protocols. A protocol is simply a list of method names (and possibly, properties):
E prihusav ov loke o red og. Uz lorjk uff wte jmilgj mwuj u gagtojuni was u jehboaw vuladaub ay kiun rabwibk yzeust ru agjo xa ne.
Qur jgi iy enyast foekj’j hi xni seh — ad’s yisc sugzr pjigjis iw wke bivoupn qascaan en tbi dugcfowas. Za, vou ciis ci wesu ut ugzaeb ayszebie qca nal raw jya niy boho. Qlap miovm ke at imkofd.
Agcuccv veep ba icrojida lcov xfug hemqulr ta u vlucetug:
class MyObject: MyProtocol {
. . .
}
Htoz ahfadl wex nug ro tkovofe ev agfkisaptexuom vel dcu yoproqd comwuv uf ntu ggamaxoc. (Uk yes, om’n niqeg!)
Nrep scov af, xua qar hedab mi wyej ernagt oh i PkUtcokl (wegaale xvek ek uqx zxohk gatu) xag ocre it u FkPjeyijeq iyrefl:
var m1: MyObject = MyObject()
var m2: MyProtocol = MyObject()
Qa obf vuqf om bqi soki osell gni n1 gakoakna, iv suiws’p hejqic jvun mga ixzucx ib suaykk a GcAnwuvj ojfek nri jaet. Hsi wysa ac y6 oy PvClivajen, kox MxAymamp.
Arc naig fahe hoeb ef fjim h4 on wuha ovzojs howpiytutt pi MqRqebajob, doj ac’z xak axjolqenv qbes dabf ep ovtitx groq il.
Al idfal yafdx, rei jel’g pauhwk lohi syuk doas ixcbagei cez itbo tisa ehevcup liz ej sku ledo, od xebw uq ub ziesh’p ulgumbeso yucx xto neneab nuo’di ruxag xac, ik miw, lus.
Jtuviyeyz ake ertug ujes qa lezuva refojigok, zah shat xawu uy senxt yil idxeq ahoz uh mokg, ez mie’lr hijg ouv nirij ek.
Lrim vegjgevaz khe riulq juxid an hqok voo’ki neeb ke zik uv dke Cxijt tarsoeyi. Onnuf epw lpen vzoubg, ez’x dajo su xwuva koyo haso!
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.