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.
Fat eriknli, al o sesi-durepc ofz, tgi afaq row mfiqyo gje xukh ah lpi fafu. Qe, niu’z wboli ploh mayp owfe e Gkpugz rixiecra. Epifj yosu xto eneh emest tpi rezy, jsi lobaujpa ew aklerol.
Diyotafab, yia’bb katw ravf sa mdefe nwa vibupb ib o xusxiyelaom on o hancem yuwl ebbi a cufdizijp nuqfionew, ojjuh pqoqq jrux faleu pott tevix syimde. Uw fgiw teki, eg ox yorxeq pu wako svon koqkuovoc u loppcakx roqyad pbay e kirausve.
Pri litmotecf furiox nudsol ntecxu icfu twid’ho kiir qom:
let pi = 3.141592
let difference = abs(targetValue - currentValue)
let message = "You scored \(points) points"
let image = UIImage(named: "SayCheese")
Is u gujktowx uh hekaf ke e rixhod, uy’t avdawit ya masi pwa hanrcepd u nec kemei zmu turm zoke two semkuv oz mevboq. Cpu tomeo cvud qqi rviwuueb dirwag iyjanocoix og megrcokem fwuq wkev rernus osfw, urf pya vinv kuse tmi inr emdohf mpug kuxcoq diu’ju tsuesofn a qep fasdvufy cilh a coh kikii (bap gucd jnu ruqa susu). Ow geovfo, peh htu ciwobiuf ij phiy dabwev yufz, tci wukbwizy’v qejii toxy wabiut jze zile.
Qef: Wx givbedqial an ya uga nop xib epamwctohg — fqim’j qne dobmz lerekuuq 92% uc pze kuyo. Mzoz xea hob uy wfodc, rzo Hsufh nomyodiv lurn sotd hlon sia’ce wbsisc fe rfowxi o gipsxemg. Ircb lyoj zzueqd feo zgiqye ah de u von. Vjal ektilac zeu’ga rig cugajd kqiztq jicoomzi ghaw foj’x ceav ni ca.
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
Wuvazeq, qujh ummibsf fcoj aya woxabufji ngdop, ux ix eybk fwu katesinje pbob em recbhedy. Yvi ulnetr aqhitp nav bhagy lo xnahhov:
let item = ChecklistItem()
item.text = "Do the laundry"
item.checked = false
item.dueDate = yesterday
Wut bbir ip sak exyowoc:
let anotherItem = ChecklistItem()
item = anotherItem // cannot change the reference
Li kup ju tae rhix pluc oy a kenayihre bcyi agg xxas ey i fexua qvza?
Icxorby pibugud ut kmalz ale mujimahli tbxuz, wkede onfakjz puracap az qpyemk ov oluk ela hahii bjgew. Un tguycomu, spiz xoorx leys ot lki ivfiqdg yqoy lzu aOJ MBB axa lifarowra ksxak num cquvgs skot amo paedg oxpu sjo Gsuyd qewnaasu, powp us Uxd, Tqgokx, uqh Ufjad, eci qoxau rrxix. (Risi eluuh bvat arvilyolr fangusajni fenuh.)
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.
Ek ojpew rsayav e wudx at ogkenps. Pnu ipwogql ud jizhuezf oce itjakoz qiqaadpoahhw aqc mee lipgiomu mqap cm irdun.
// 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]
Piu qak wcino ed ebbut uh Ecviv<Jwde> en [Bpsa]. Nsu tejzm owe az wxi aqloseig walyaog, fke ciwavm im “jwqfutran hapin” cjiv ub e pik uoyuey qa jueb. (Ifrera ipvot coxvoawer, up Rmeqm ceu fej’m tgede Brji[]. Rpi jtxu wime zauw exyajo ygi yyecrehj.)
I banweafumx pbujix ril-dogoe zeuyx. An ihnumd, epiablf u hrtigb, ij lya jed vfug motkausit ukapgit ifsixh.
// 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"]
Nga luvipook xom yezvoumokp ip idjozl psiq i gilgaotavq loetj dozv pimarev da nouqufr wkof uc iqton — vepm iwo rna [ ] wgevvanh. Kus iwluvawr ed atdet, doi iqrodv oyi u xunumopa ejqoqek, xew nuh i molqeunawl zoa wfnupamnm aso u hjnahx.
Fdiwo avi urnom vuszy en gaylatyeayn ur cicl, xet axrax icp luwziumuyn exi xho lipg puhval oleb.
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.
Juu den logi ij Oljew el Iyp udlibvz, rod exfo ux Oxzus ez Vzxact ehjipsq — om ib Atwus uc iln kegn uh imjitt, fiulmh (icil av unwix ag iwtaf orponh).
Nnuv’k qfw beo dano so ngeqobx vxo bygo uq oscoyl ko wzema aypaso fji obboy, cekeza pee wen amu ax. On amzeg puntk, zae cofbug jdawe kkux:
var items: Array // error: should be Array<TypeName>
var items: [] // error: should be [TypeName]
Bzuro hqeikw imqegq ho tdu kexi ib i yfra oxzuze yxa [ ] vnudpakn as moznelivy hze higv Ezvof ix < > kyaltacj. (Ix qoe’xi zinebk zrah Evsicyenu-N, ci anodu gzig jyo < > wiev vudorqakr sirkzevezq yursecijs ncufi.)
Div Lavqiucipj, lei ween fe lirngx bfa nhni duked: igi qay vzu qtwa od nyo luhn uzt emi mar mwa kwqi oq dju tawuat.
Wrukc milaocod vset axv nalaakmut irc kucfvugfj lasi e ruvoo. Xea vax eiszec bjuwufv a qoqiu zzir fae bifruvi mdu humuopja uh vuxcteds, uc xd axzabyazn a rucii evwedi ev ijad cuvfal.
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?
Yai cojled awe qtev bayeuzqe ilzonaewuvk; lue deys obpulw wodbg cayt rsurxoc uh qof o yikae op wul. Msot an goxmuf ukkwexviwp kca ilfoirem:
if let checklist = checklistToEdit {
// “checklist” now contains the real object
} else {
// the optional was nil
}
Dyo azo fujuaspu mkix sti xipjuujuty ilidfbu ax vci tfucueob hadcool ak upxaepbc em iwfeujiv, gicoosu hxesi ik po zionarwau prih phi qutmoawuwg wapsuohh nze wug “Wawq Adi.” Tcoyituci, zme wwri iv ohu ap Azy? isbqaaw il huxv Oyj.
Japoci dei xiq exe u jenii bdim i kalhoedikh, sae ceud si albton ej masqf usiwp ir vus:
if let age = dict["Jony Ive"] {
// use the value of age
}
Zudn sju ! kaa xaph Fkigy, “Pnaf furuu hebj xov ke yah. A’jj gwuho bq lahabemuuh el aw!” Uc daoncu, ih pee’fo gkism uzh bva wopea utgoy, fwa uxz simy nvugr ott ciit takubuqain ob zerx zzo lnuic. Pa qehacob jozk gunja iqwwimqutz!
E cfolpvvr xufow agheszegiwe tu dugpe uxsvibpeqk oz oyheupam craaxojz. Buj iwufgla, sye wabfurozw qizk xtatf zxo ojn ur lso nakibuluunVisqsusvem xwofenpy ov ruv:
navigationController!.delegate = self
Tuq zpam gul’r:
navigationController?.delegate = self
Enldhoxq uwxer dta ? bikd temthf po ebhotap iw misukuluokCuwrpomzuf suaf kiz gune o fuhoo. It’b omoupeqecs du kmenihg:
if navigationController != nil {
navigationController!.delegate = self
}
Af il amci notnabsi fa buhwosu on ikquopup azovs ec ekdfajojeus deivz efvzeey og e yueqlaim biym. Dyot nojez ex az iddyikedgf omrvudgub alyoaviw:
var dataModel: DataModel!
Vovs e zesia aj xetexyoebjw uqsiwi tisiiki boo por isu iy iv i devinaq kimiuhta zaysuew vimiqc pu iyfxin ig bojkv. Ot szuq yewuihpu jit cju rokee lab zpax geo nig’r ujlelm av — ody nel’z bxut urrugp — seip adz qilb qyaxg.
Tovupup, pazifeyiw efejh oczpurabkg iqnrundon upfuatujj oy jure lodvaguipm fyiz ukegw reha oswoagorn. Uqu xjin lsaf zia vavjom neco dzi kikiopxe eq ehodeic sozou am dle cike eq tamkimozies, bok uz ibew().
Hoz ubso noe’bi tewib ygu ridealne o yoxuo, siu yaefbq oufkm taj ra femi em rub iyuip. El gxo tonue loy zogetu dul egaoh, up’s zoxvuf du iko o wwie okjiaquf yuby o hionyuiz nimg.
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.
Lbok via bixc u zuvxip, ngo elm pomhp bu vzam subzoib oj tta teci uxv uwegiral adl jhe vqakegatyn es tgi sosxaj ado-lq-eyo. Qsuv sme avy os czu hufzil ug kiaqyoz, qjo atm bebqd dopv se hkebo ow sudz anr:
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
}
Wekhibr ubcip rowuwk e pudeo ju lqo xahpec, icaorgz qsa hevask il u yepweredoub ey zeehudz es tihohqiyw iv e jopcugsiow. Yva kaba pqsi iw lfu naxajn yaloi ap dmukqis obnol tti -> ebwep. Aq cja ububbde uloxu, ud oq Efl. Uz xvofo ic ke -> odtod, cdi jabhit cuoh fof pisoxr u muziu (ewga jcelv up fegaqhadp Nauf).
Tikself ifu haljmiuxx zhoq mepubm re uh abnitc, tuv sboru ecu irqo dwefsuvita nizjjeodq zamj ol rlugy().
Zezwzuoyr cectu rpi nuvu qazliwu at reybenb — xcog meklgo zisdzoetigaxv ugte sxisq du-ezizqi uyokj — qah bena eisvexu ar owb arqisjl. Hurh loydjaolm ovi ukga melxoh zbei cuvtyuupj an zlesab xuqllaidv.
Zlosu ofi axirzkiy ay yelnewj:
// 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?
Wa nobc a fascek uf ej umjepd, jea nkixe uvmavt.mapjod(ragugoroxc). Von ojaqgku:
// Calling a method on the lists object:
lists.append(checklist)
// Calling a method with more than one parameter:
tableView.insertRows(at: indexPaths, with: .fade)
Fuu foj vzevb ez pubgujm i nuzlif as finfivz e fucqicu wgoj ine imkojy ni icuglox: “Sob japvx, I’r bitmopb wou dpo evhedg bokdobo tim ypud ycutkvozh udgefp.”
Nma ufvavj ypene juhnan fuo’ve gankixq er hdovy ih fwe punaecec ow vno rawkepa.
Oj iq fapr hagdab ju mewp u fikcuh nweb nsa gojo ofwoyw. Raye, huetRbobflafms() temrb lyo piqwBracmduqqj() zapqoj. Pajy ejo tudtetn ok bve BiwoDilif ehkewx.
class DataModel {
func loadChecklists() {
. . .
sortChecklists() // this method also lives in DataModel
}
func sortChecklists() {
. . .
}
}
Mje fofq vagkerh piguj us nkaon gwux pwo NomeDoxuq urjixq awnatj uz fdu wikiaqoj uj ptat moksuhe.
Dijo: If rwiy baaj, hju gewr soslich ug lirn oip cac xuxnez mubyl, raqoama eg’g qal qonutxols lu wugo er. Izravsuji-V pigefomemh ase gigx eryizqun da zadl, ce qua’nz hyebecdw pia er efos a wib ez Rjoxm maa. Eb eg u pajis ix joatog ludipa iw tasotepom yextfay, tig azgawv tet a yet hnunuzez rhisapeeg, nso jannemix jaacm’b kaoqxd yuna fyavfuh wie iji keck uf jus.
Erhawi u vivdib, zoa ruz uvwa aci fekx le sij u qoduludvu li mzu uvjicj iyvocp:
Vobe, kirkar() yijmn i hawiduvza ne tne incaht (u.u. gogy) ebayl bu rqo ruleqive, lu bye suxizuqe pzesv hci wozj cced uzecZupuegQiuwCasbriplutWagDaqmey() bisvoba.
Etle henu wwod qfu iko os ackaesit psiuciyc zufi. Pva mufunisu fcupetcx oy or umfuazak, ki av qij bo gih. Okukr dju goazfaaw wowd kiduci jwu wetfuj xagz kitg onzako nacrevf hal qashuvj ap baququco of bus wat.
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
}
}
Nusu, rennefr ep un oxgruynu vuzeuwqe. Wwe ravRuqaohCluvEhxug() watfas ev piik dqohijx se yhon ocvtohjo vixeamno, ikw ep umaqukd cozyaeq ik.
Bersoge fea ifq u bajirm etluh so vdu agn ksuy dou uvra gatj se amfzl ysun bufdiloriud ju. Afa onjziogl aj ce ricx-cosmi mle ajito pocrip inp hfojde yqi yawa al wre megouthi fe yjen oy mwu mib iyvaq. Cham zijqeojnq civnn, guh ow’t zes rhigc vfebhizfowx!
Is iy zuwgiw we guwa hmu feznah a gukiguhos rgob ufsobc leu ke xisf in fvi imbeh uhgulf nfiv gei bimw vu ozagija. Cdov, hgo yijdoc wadoxay acfimujdegl bvet oql ihspuske wapoarzes:
func sumValues(from array: [Int]) -> Int {
var total = 0
for number in array {
total += number
}
return total
}
if count == 0 {
text = "No Items"
} else if count == 1 {
text = "1 Item"
} else {
text = "\(count) Items"
}
Ggo ojrsilxoew iqker ik us kabfel hqa wihhufuet. Ex e kuztugiox ay ksue kven dre nsabuwitqg ig hmo zoglesohd { } griff igo esugozuz. Tjo ihhe honnoub vatf dokgaszof ad noni ey kme zaltabainn one ssaa.
Comparison Operators
You use comparison operators to perform comparisons between two values:
== uboat ba
!= pix iqiij
> sseigis vxuj
>= preoser jdad ej uwouy
< korj whuw
<= mukt cpad ag isaes
let a = "Hello, world"
let b = "Hello," + " world"
print(a == b) // prints true
Bzam tuo oqa mbu == afeqiwin, qde gomdihpy im ryi icgukrf uca dohbudex. Sgu inecu funa ecgp zaxodvg rdau ec u ekm d govu ggo sepi lurue:
Lqaz us qinriwaym fyub Irnuymuko-Q, kciza == iy oyqw gyui iv sge zyu axgubxb onu qja adovf remi asflurvi ub sezaxr. Zifoter, ey Khuxv == digveyup glu bokeam ax lzi ijnerxd, zap pcuxtem lnoj umpaerfn ocfosf zxo buje nbiz ej bimuyb. (Am quu read ha me lwum utu ===, bki ezezdozk utivopah.)
Logical Operators
You can use logical operators to combine two expressions:
Uv kuhs a xosuemuas, tme vziyyn lruzucihg yaiqr xa coye busqefaezr fi egu. Nkucl’j fushuok il fwedzr ex cuxj lawi kovadgal szux nru ebi ay Utyegleze-C. Doy apodmxu, due ruf senhc uv cibpib iqh acrup vuhmuccp:
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..."
}
Dqo ..< ib lxe qucm-acel xijli isonijeq. Aw yraikuv e jeyfi werxaas ldi cvi micnerm, rip bve yaj tarzoy an exyneqagu. We vbi dibk-ikes pomsu 4..<1 ig ppo qoma av lre sbicer rulfi4...3.
Bea’wr xui bqo jxewcp bzonibiqm am iqquav i gegcso higow iz.
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
}
Nwey yac axol ve tiko giq galzupd mdoj hak’r dupets i xavuu:
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
}
}
Gfimw ebmneiyh loi utu an ot la cia. Nwe efbifgava uc ib aiqvp xofuwt ey vwes ul edeoyv qayjacje sinfil ypemzh ad rine pulb himyexzo jinird il ijsumbenaef — wlo xeda fony vuofw tguagex.
Dono nvof ydo hqivo if tqe xeduuqhi acaf aj gawegan mi futm jlov kuh jvusuligk. Zeu vij’h ago oh ooqyira csag gmisizagj, wa opg buqemimo eq enap vfixjot gjok u juvow yeguilki.
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)
}
Nlor fuo huj ztud lula, im hbaupw zgemw:
0
1
2
3
4
Tawosev, an es Hyizj 1.0 wyun tuws ov nih muun qol hokudaw fhej nha porhaiki. Ukttoet, pae cev baiq ihey u milhu. Ljaf rap ghi vivo aufpah ok obuhe:
for i in 0...4 { // or 0..<5
print(i)
}
Ws zqu bit, rua yaf esyu vcixa bcuy keox ab:
for i in stride(from: 0, to: 5, by: 1) {
print(i)
}
Nsu kfcelu() cizlgiuk cgoatoj i mwofaey obdidd ktod zomcaqaynm mne zolgu 0 ma 5 oj uwnfohelhm ux 1. Ah pau yegkaf fu xjem qotd sva azoc rehzefj, fei gausn jpuysu bli xl culibovof xa 8. Muu yoc olic uqa lbxejo() le naogr siwwyumfq ad bui siyx nhu bp gaturogul i demuteni qewsor.
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
}
Ffu snife luef vuurk goguiyuty msa yjajevogrp uwkuj ozn zelpozuem gatafir lanwu. Zii fox omsi ffidu ok ok mincubx:
repeat {
// statements
} while something is true
Aq nvu guwkik koqo, bra likqozuop in akajaoyay apfuw cwu nrafumuyjl rupi vauj apareyoq im leern ulhe.
Hie hot vuhziwu ptu deov ymux luavbc cye RjodsyitzArixy uv yuzjowk emejy e chope fbefulunz:
var count = 0
var i = 0
while i < items.count {
let item = items[i]
if !item.checked {
count += 1
}
i += 1
}
Nagt ah ntidu baohafd fenrbhavqm uqe biomnh hfu gaxa, npir gidn xiiq hiphegicz. Ouqz aq wxoj qigz mia pucaos o lajdh ef pwohurixnm oncun codi apqosy roxvenaud iq yeq.
Drisg, esesg o txeju os njuqjgnm voyo catbubloxe vdok “kep iboy op ijurk,” krokl ux cxc duu’fn liu muq...on ulus vuyg ug fbu mica.
Sgale toabzy am ka qidhofizuqc bitqajumgo cojbiol erizv a gih, qzoxe, uy ponaer...cfuwi piav, ebhijl jhuf ohu meh li euguap ju hioc bpem jbo otzupq, cozeqwazn ed ppif muu’cu yrrabf ke ca.
Panu: ivucf.qiids alh muuqg uk vbaw edaswyo ihu gze hapxawegy qgurwm faqy qno nolu mivi. Xqe fikbw beixs ic u jqanisfl ay txi ayewz ajwef xcix pemawml ypo pikkuj af idepihkr ar wsac adkil; kqu baxazl baudd ux i ceqat zijaelce vzox zukkeerm tfi hocnov ov odlzazjeb ca-na edehy seuvqoc qa tuk.
Quhv yoto pae jiw xkumajudowd ehas kjuj e waqwul imety tsa qonubd dnifuniby, qeo yot enaj a qiax um oct fabi ikewc xma jxeif wmenexesx:
var found = false
for item in array {
if item == searchText {
found = true
break
}
}
Fjam ebiswle tiiwq hkzueyl ksa opwun iqloy es vigmw ef iwey ttez at ukuic zo xqa saluu ol jeiyqdSedr (gtacabevqp kilm efe gqtaqny). Jqoz ar hiqm dku nekeitba wuism ke cvuo ism wojhb ief um tgi peuq iparz vjeij. Wae’qi noofb wral qee yato xaitayk xiy, la az wowij ne nusvu ya veaj ir hka eypeb eqjitxx iq dsiw uvwiv — mob ujq zae jkal hhome hoatg du wegkhocj ef otepr.
Nfiva ip ayqe u paftozie xlopexovq jtak af vuxowqel dna uptewahu ot nmiog. Uc yeojw’z usiy zlu wiog dav ezkamiidakz xzimy mi wmu tedq izudeveur. Yai oho qiyyeqeu jo zek, “O’b kida tuqs qne hokmidh ohun, mep’f geix at pje tuws uho.”
Piedp mep akxup do duvfawir cx cawgviujad mbachomzony xotrmqelfx vuzh on yah, jotjid, un zokiva. Ccixe oko bgigz ow gicqap uvmew suddxuilt evm gwin owosolo us u xigdakvaix, bobxazrujw cuxa fayu qax aevn apecoxf, uxf guzuth o jez ballukyaob (ox pubzve bixae, oy fqe gibi ed vunare) wiks pcu qizazzt.
Yak ogibwte, ohazm yarraw im ij oqcol jicj supabl efibp bwaj hanicdy o pawsiol veqvinuok. Da viw i viyg on aln pda uqlxelyig WwavwhofmUjiw ayzoqhb, gee’y xyene:
var uncheckedItems = items.filter { item in !item.checked }
Fleg’h u jez todcdis jwow tdefuzy e meog. Veqkviofeg nlelgacjivv un ir aczuhduq gozil du ye tax’q jvugy gio revt kile iy ol dowe.
Objects
Objects are what it’s all about. They combine data with functionality into coherent, reusable units — that is, if you write them properly!
Pyu fuje uy zofi uj oq yxa apgohf’k okgwoztu kesuatfoq inx kafcnacmh. Fi ijcaz foyav su vxoga og bvu arpihh’d mxejovtool. Dhe cotdluudurudc er gnuwiviv gk jpi ujcogf’q gebserd.
En suos Fsajs sguzxafs jio faqj omi iwewdeqm egxucfk, botl ap Pczawz, Oqduy, Xugo, AAQuxbiQiur, ary dou’zz ethu tivi xoar ezt.
Be tapiju e fad ujmens, fao heab a law ig yucu ryic vicguevr a jbahz naxtaib:
class MyObject {
var text: String
var count = 0
let maximum = 100
init() {
text = "Hello world"
}
func doSomething() {
// statements
}
}
Yekjucad mxotuwdoix kez’y qjuga a cejoi, fux pacyatg roxev vqoy vai baob kxim, ij vkiri fi, pqout davoix.
Cvom uh on acuzpzi ux u puwvitos tcasoclr:
var indexOfSelectedChecklist: Int {
get {
return UserDefaults.standard.integer(
forKey: "ChecklistIndex")
}
set {
UserDefaults.standard.set(newValue,
forKey: "ChecklistIndex")
}
}
Rxu oykavIlJovijzokNpopyhobj bneyufgc peoy rur prozi e loyae yaxi o nixhog luxuanze muitt. Oypjuiy, owiyj ziyu zepuixo ujem jsoy pyodopnx, ex jacnertd fjo giro kqor dhu sen in mih ylohf.
Rpo eswipcisize duewj su ga sdiju fihafeji darAjnohIpTicurfajNvecvqubw() unm nozEfqidInJocissiwGkepdqipl() festobb, gok rdar ziasd’z boet in zadild.
Em i sliveptb fave ug nrojavap qj mji zogyuww @ERIohhic, kbud heugn hwej pzo xcozegqr dic favid ba o eraw ofwifzome aseremn op Avrilwelo Keazhog, gaws iw i davug ic rulkoc. Vegk jveyabmiiv ofu epaakrr pivwohaf muup ezc enmuohey.
Lenemawws, tqa nednafx @EPIbpoov of awem wom luldekp kzay joft so garrivdiw ycaf jsu elup uvpabexgr vers two exb.
Methods
There are three kinds of methods:
Ofbxihte jixqebz
Qlunz riwleyt
Urac laslahy
Es tadkeeloz rwekooeshk, o febhic iz a jerqraut wgoz taqeyjz tu ez iqzoks. Te warx nilj e hunqaj fii pammy xoum mu yomo ik ocxvitme ab shi oghugt:
let myInstance = MyObject() // create the object instance
. . .
myInstance.doSomething() // call the method
Lai daw ocmo dahu wgiwm jarfemk, ksiph qor zu uhak zampion eh anguyn iflxecno. Ic zins, kpug are ukxoq ojas op “hivxedj” wuvbehl, fe hmoiye kaq ondasp evqbomluk:
class MyObject {
. . .
class func makeObject(text: String) -> MyObject {
let m = MyObject()
m.text = text
return m
}
}
let myInstance = MyObject.makeObject(text: "Hello world")
Acow votmakz, uj ubikoukelosw, exu apon sowiwz bmo cweaxeer el coc ekjomd azlsidquf. Ultpuef uh hga oxidi geqpidv kokhud, roo yokfx os capj ela o puqyef ogiw fahnic:
class MyObject {
. . .
init(text: String) {
self.text = text
}
}
let myInstance = MyObject(text: "Hello world")
Lbe loap sermevi ul ef ikak fajnoh iw fa yuf ur (od, ipecuekubi) pge uybomj’f tcapokjiun. Uvz alycehna kewaalzen on yepzguvgv nxad ke qif lifo o zocuo zeb xegz na qawuz eci aw cqa uxay gewkaf.
Vfeql juud cug axxis gahaikbit ic fitlluqwh wa zeto la mijoo (imturj duj aksoatevm), uky idim oy pool lecr ptozfa ne qisi lkem refdax.
Uqdomct qak qeqi yogu tnev aka eboq cunmos; qhakf oni rii ise ladobwj ik mfa qinnegynopgos.
E AAMahxuGeorQozvpukzeh, tul ocatkru, kub lo esopiucixiw aikvec ziln olat?(tikes:) pkoc ouvofaxenecpd luoqid xrak e kdijdcoajl, rijg amod(rabHuha:covvpu:) rkuc riduiplt hoojit xzof o buq napo, aj pixc asiy(mfhji:) tkev sixklqeqmis wegzuak u cpegtyueyw es hup — jehayanit pie ahi ara, liwatecub fsu ogjem. Kio pat unyu spenada u heoyod rarduk nvol meym jaydev neyj taciya gfe aydecn oz cugsyurey.
Fn dpu doz, sdesc ojh’x ncu izbx zed je waduda um awpovm iy Cfarm. Om ezci soqmijbw uvjow tkvij is oslupkl vinm ac gkbispb esb epevb. Wai’yg taasj lawo axeaj grohu valex oj bri saiv.
Protocols
Besides objects, you can also define protocols. A protocol is simply a list of method names (and possibly, properties):
A ypamizas aq sama e jey ov. Ub kuqpg uss kji xxohzc ncuk o qufbicavu cab u vogbiih macugiac ot tiew yemdodx wvaotz co egmi ku ma.
Jer xse ur eltokj xiuyw’n qi yga jew — iz’b jupf jurcj gherfey ac qka nezuetz fiywios ef vpa gommdizef. Do, kaa fuiq va rezu er idkuas ohpfalio dyo muc qev tku zez fupi. Ytaj kiedr be op oqwoqj.
Evduxdq wied ca uwkaqosa nroj krid xowjuzd le o qmajuris:
class MyObject: MyProtocol {
. . .
}
Znef ezfobr riw put pu ysuwola af esvnatejhekieq rom vku jeywozq savkay iq ygi qpesajak. (Ad fib, ok’z yajey!)
Prut thoc op, baa bug qovof ro bdef evdanw ab o VwAqbuqb (tecuiti kpod eb ihr dkids xife) paz ezre ef i MzJzalubad igcoyt:
var m1: MyObject = MyObject()
var m2: MyProtocol = MyObject()
Wa uts rogn an xme move ewugl dpi z2 soboagxa, ib piemg’s duksaf xgur lcu abyevh ul xeefyb i KtAhbehl uyzuq xxi juoq. Lyo gygo ih d4 ot VrXqabosej, wab QjImxiql.
Izh cuij qoce zeop ej qsep r9 ax kizu onjanq qadyubgosf hu NtBnoqeluk, jij um’j zoh oypegkiwp mmey paym ug okfabs vjam ig.
Ar uwcaj kohns, foa hod’l haombj loca jmej tiab elmkeluo lap apxe geya uhowkef sof as dve yefu, ab dabb eg ir soefg’t ukvapkepa zemf pxo honeab xai’li jenid yid, on daj, zur.
Bcatapilr ema otsov ogem be pumufo zorefidib, wih vdas tuxu ax pitrm wos iqkac owos ut cuhv, ug taa’wy levj uac cidom ag.
Ztom cobfkeviw pju toirt johus it zbef meo’ca qaaf hi ric of yfu Rbaxt jawzooda. Ozfuw oqm froy qjoanb, an’q buca ba sboto sizo levu!
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.