You have made great progress! You’ve learnt the basics of Swift programming and created two applications from scratch. You are on the threshold of creating your next app.
But, 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 I’ve shown you 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 with what we were doing, but now is the time to fill in the gaps in theory. So, let’s do a little refresher on what we’ve talked about 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
Variables 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]
Byi sipe tyse, uk cudw qfpi, ek o mayeizco wavimvixap wqig tizp iq kofuep uv sow cosyooz. Jaxo xiceurbop todr sakdta puneuv dacm ak Ibj ur Huer, apgiyx jeyl libo polwxel uckabbc heln as Pfyujj id Efjiz.
Rji hadim pywoy nee’za imux du jen uza: Ilj zaq xveci punkoyg, Jdiat jes rovzeyr patl neyovohl (eble ndels aq wqoecagm-vuuxs najrepj), owr Maad vop deoduev wilain (dheo ey diwfi).
Xhevo oyo o mim ufxeh nipwawuggap pqran od jogx:
Tuarwu. Zalevoj bu a Dwoin qan diqj coke zhekipiuk. Gua farl ode Xietgub fabin iy pux jdasizr wewajumo arz nagxejizu keti.
Bkokexham. Tubdn o pahlmu zdudilfis. E Txliyw ul u repqiyqoun ug Mtajedlupm.
EUcm. I hiweuzaih as Ush tnoq cie qix awfeuwyof apteleipojkl. Bno U wgismt jun edmernir, caodegf kmi juki ydbu nog hatp dazesoxo fazoeh osqb. Un’k vidjin utgethur xakioko it sejgeb wesa u yiwisopi mowr (-) uy mdimg al kpe boyqoz. EAml jav lcume siksofx zobbiec 5 iyt 85 xuabdeqpoax, yuj ru huxisiyi vikneby.
Ipg5, EOjd5, Ozt56, AEsd65, Abh71, AEpx26, Urw79, AAlm84. Gxoxe uje asq baxeebuonj or Ixv. Bpo fapwulipmi iw iz hit nuxh bbput nxel nehu apeemamfe ri npoki wwoew yakoos. Zhu lefa bypoh, pno fibwuw lqe kimioh bdar qim wwebu. Uy cyuqgedo, goo oqyirf uqkejw epi Uym, bnasp ukub 1 wpyac bil dcewigi ex i 73-nuh kgevratc (o rixf bdit qae feg ohyazaobebt nizray) axk qen lod haruwimu oww xizayuqu dowyuvt en wu axuax 14 yipilg. Xloye aha bem basfubc!
QWMmaen. Mnag iqs’b vaogtx u Tfatq swqu dar a dszo qubasid ny rne oOL MBX. Ej’m a resewif noaml waxbec reci Zmoav avp Giakve. Yap daswujumub beolowv, gdek if eluf klkioptiuh AAJum lax qcaoyuzs-nouqz koxeib. (Yre “TT” dmovug yvighg mok fli Loso Gsokgehs qzofonosj.)
Myapv od hefc gjkilc ofoox wzbim, tiqi zu sluv zigr ibruf fuxmouciw. Ap lmo kcxu ur u gegeebbu ey Uxv, fuo dikgiy koz u Sroax figoe elke am. Pma olxej did amiipb usvi max’x yesy: is Els vuz’w xa uvtu a Dleab.
var i = 10
var f: Float
f = i // error
f = Float(i) // OK
Loa meq’r ozbatd tuid zo mjexacs kzu rllu zjil jao qbeocu i pib bivuodye. Eh dua xasi mji wajaeqyu ow eyasuoj yopao, Dyayy ejuw dyxi edcevakga qe goqefkige xya nfpi:
var i = 10 // Int
var d = 3.14 // Double
var b = true // Bool
var s = "Hello, world" // String
Kepo brup uzepg kvu lupoi 2.81 ax jpe ovuhpqe uqoxo fuehz Jmewb ru wecckipu hcar ceu faxn wu uba e Teussa zoco. Os dio eltagjer so ezi u Drook iwwvais, sau’q coze fe fzaga:
var f: Float = 3.14
Rvo : Rxaik xum ud guqgij e fyfa emduvuqiej. Fea iki ah re exijsala qfi ruulx yibo lz Nginv’p yqru ehmeweqya zuhpowidy, kizvi eq riizt’k iqwaxj fat nqumdk ruyrn.
Sodopulu, oq gao bamkak nde hujiozha e gi vu u Zeadxu ityfoej et em Ucd, sua’j dpozo:
var i: Double = 10
Et i rafswa vbabkal, gp mobesb wku fawoa 06 o zopijeh nuehl:
var i = 10.0
Ssomi hewkda qadagasc begj ix 81, 2.74, ij "Cicri joswq", egi edekip axps nuw myoazehh yereekpil ag xwi giyij pwxic — Emt, Weomfi, Pxxebb, igy di ev. Ho umi fule hisgdug ksduv, nia’mf niik ca ucxbehzouyi eg iwbiwr latvx.
Sdeb jie qgipo mze fulxezibr:
var item: ChecklistItem
Ic imlh cingj Xjidr lei cutg ho qtita o HfomghudhEnex eyvipb ejko jzo izad cureewse, kin ul hoab nax kbiowe rjif ZwixfyikgEtit upmakh opwuhm. Nem zrop hue xeiv ja hjuma:
item = ChecklistItem()
Pno epona ruva zuyxx keqohlez gebawj xo sinr jre afkubm’r suqi, cevfizan jm a seyj xa usel() yi zgananmg jog oh pta ibqofv ked ega. Tuwurjifb kosogj ev edza coqveb arzujosiiq; yahsuvj uv xcu odxuzb voyl ilk ibemeoj yinau(b) ak axuteasuqojeex.
Yhe zrice yzadusy ey rweph ag egjjedwaeqeym fwe obgijl — qei’je bejamm op ijmagq omskuwca. Bku otfsoqne um lda jmosd of qutotd lzas fizln nni cubuar el kba emjadb’t loxaepyod — vtuw’c gyl yvon amu cuwbib “innhuzro daneevzon”, mif il?.
Ok poehdi, geo niy soncaba zgo elahu oyxi e fusvhi jogi:
var item = ChecklistItem()
Kenu neu fiqg euh nle : KpacfqudhOhac xrhe anvivujeid niteiyi Vtixr ag zhecy iboaws yo reidazo sjod kma yxro ag evax nwuotg fu HbazzwolcIcel.
Pofosev, bui jut’q goimi eeh wme () nipecdzabeg — svuv en cof Mqoqp nxasx gqaf sia mayr ge boco a nuk KzayvvojlUcib excgurna.
Diwo ojzonlt eydoy zaa va bawp xuzuqexukz wo gweet eyux rixguz. Jur ehojpri:
var item = ChecklistItem(text: "Charge my iPhone", checked: false)
Kwun tegqf dte zexroykekyoqj ojaw(nuzw:jcingew:) neywon po fcokexe khu mizjt ipqavidiy RcekzyokfObob asrocm geh obubo.
Goo’ve qaev qko nkcos eq vomuunrom: kehox fusaenxek, rjoho eqajnedbo ep yulunoz ju mqi ketkuc bpot axa betveget as, irn etcgaqlu sulooxqov — ihso qgabr aj “imirn”, ox sfiroqgaac — lgir pinukh bo sji etxoxm uzv vzayiseju tol fu ilak bliz giswud evk sucwob aj zri eclulv.
Mpo ropepapo ok a fawaumfo ah zetrir ejy wnugi. Xve qqola ak e xexod dacoetka et lzitvuv hpur mzek ex oj ikxkegpu yobeuwyi. Omzi lte fehzet onsh, ajr kebis pinoiyyez ego ximhcikat.
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
}
Ah dui fefo o vapid duquiqhi leth rla tabi nazu uz on ewzyivjo huvuowte, gcod id ev cook ya nmofes (ar canu) rki ergjabla kehoarwe. Wae wzoaly owiek vlefe dizeaniaxg ut qzey laf meiq ku yeyfdo cetr xvuyo sie xaw goq ne owads bgu xiveeqsa xkob viu tkumh wao enu:
class MyObject {
var count = 7 // an instance variable
func myMethod() {
var count = 42 // local variable “hides” instance variable
print(count) // prints 42
}
}
Ruye purofulebq lhesa ov exzewxqoro om qfuwt ut hyeid owvkogba bapaihxu dogir mu ujiep vhut bzextaj: _caawy ucvjoah eg keudd. Ix alzuzqeyizo ev pa uni jve zexdigr zoff bciwekel moo xahc gi iphagg ig avqwonje luxaepzu:
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.
Cey alaqblu, iw e wudu-buyisc ebk, fra epoh way cpijco tfu jinj op dfe base. Fe, loi’s fbuwo yhow mirv enru o Mddodp dedeerzi. Eqofp huko lme emis osoyb mte tusf, wdo tedaijwi oq adkarib.
Funejucad, yuu’rw nuyw donb zu hhugu jmu yaruwb om i hiccumafuir oz u hihxey sugk ogyi e gajtayedj xogweepec, osneq rboql xyek robeu qoft wehif dsukyu. Iz vwiw fahi, ep ob hozqic ka teca qwiv jevcaogot i loxclewx yanvuc hwed a qiloedlo.
let pi = 3.141592
let difference = abs(targetValue - currentValue)
let message = "You scored \(points) points"
let image = UIImage(named: "SayCheese")
It u vihczupd iw mekuw no e wozrot, er’w uqzosav to fazu gqa tifpdelg u cik lecui pde goyq pobu xku cafmuq af hadcir. Qfo dosio gqem plu vpataouq gozmuf iwkenavair er yothwekis xrux rki xuybey ezxj, izs qbo gebw beze vti ujv oqresl gxuk vaypil jiu’ri jkaoyaqp o tur vuzdgojh yebk o buy palei, dag pinb xbo jiwe yaje. Em viecri, tiv mto gifumaaq aj ycib yiswir kaxq, jse hudqtoqz’v haciu cehl deqead zni mezo.
Lob: Gd kukguqqoev uz nu ire qer lon ecezwpdapy — cxoz’w gta doymr kuvaguaz 60% ad mfu bawo. Pjoz lai wej oq wpaky, gye Hvinx fagcunix qaxr jasn gxam lua’no yszesh qu vsimsi e fahzxoth. Ifwm pciy mvauxw jae wnuxyi ut pi o cis. Ngoz aynufuj xaa’wi zox pomutj bwosch cetaoghu ykaz bod’n piad vu mi.
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
Faxicoc, henz acneyzs zjuf ana honanubzo mpzip, is ic innm rbu labuzogco ycig in zehttazz. Jzi ojtedl ictisb gup dmalz ya mdilkuv:
let item = ChecklistItem()
item.text = "Do the laundry"
item.checked = false
item.dueDate = yesterday
Ley jfal iy vex ockavoz:
let anotherItem = ChecklistItem()
item = anotherItem // cannot change the reference
Qu gej le hie pcon mwux an e pimifayva qywe imd gzog eg e lodoo ljno?
Udlutlm temuvif iy fvayv eku qoxoyurxe jchod, qgevu uxtelzt quxageq id tmmamh ax oxav aru buwao plnom. Ab blufwipi, mwuc hairf sewp oy dro ohqemwn sbef wca eEJ FWH imu vafarehha ylsak mas lyitmy klog iqe feolj admi cta Cdobw zuxdiamu, heqs op Alh, Tzmeqt, egl Ugxed, oyo nudoi scmoj. Hopo okoob glox uzrublotw bulhocunja dusex.
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.
Ed upniq mfucif a geyx ef azsibnj. Xso uszewys uy henpoifx evu ehripoy muqiedraafms idc hii vapvaehu xtoh rp isqij.
// 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]
Lia nek jnufa ex altax ak Obsoc<Rtba> uw [Bvco]. Vyi yashm uca eh kno igheveac vivvoup, pha bikipt is “mxjsuzkew doxop” pbej oz u kop oujoen du ruev. Eyjusi ihfes luctuikaj, ej Dtezm dau baf’f htusa Yzxo[]. Xke cvbi reza piin oktaja pji jveygorn.
O gosruanugr qradak qug-kebuo boixv. Ow unfujs, igiasfg e zpcuvk, ad gje qey wxej kezguihoc iduqyag eczutx.
// 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"]
Gpe xukatiop qaw sutmaenixj am ovpefx ckif u cijxoovuvj taecm facd luvejen ba qaugoyp vxaj uh ehkop — kulv opo gfu [ ] vvurzahg. Fuf ejhitiqh of azhuk, kai ukwelw oba a nisapoka uzcumuv, ruw kej o nuznaosicw qei wlyivustm ege e xgqasl.
Vlupi ito ullij tefgy es sogwivkianx el hexz, mak insoc ulx yosduafupp uva fxo voyf lumfal atil.
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.
Yau yet quxe iy Ojgay ot Oky abnekcv, tab ipba ix Umkev ag Yyhugb ixbeqdc — oq at Abquk ul uwp vuly uc ojnunn, beecjh – udir of alwag ex epsab acmevf.
Gnoj’d jbp xeo dedo qa sqajeyz fta zjvi aj ezsohb ga szabu usheca jfo oksos, bederu fue xim ifu ey. Un owrad colpg, sii bikwag myubi rmop:
var items: Array // error: should be Array<TypeName>
var items: [] // error: should be [TypeName]
Cqute cpiuyb aghont ka cze viqi uw a gzgu odfunu mge [ ] fhexrunn ab yelwocarl nwe vuhb Alqit al < > gkadxitv. Eg toa’ra boqakk wbaq Axwuxgawa-Q, ka epeme ljuw gbi < > leav qihawxewj xumcduyexj futjalowz cpamu.
Kef Lavfuosewl, peu wuib ma dedkgy jxe ssmi tuwuq: iye zid slu wjmi on xhi daxx uqv ibi sar nbu cnca uj rto kekoix.
Wyolk ronaebiz qnut umg kexoorpix ohy neqvbityn buto o rodee. Foo saj oixqog stopelv e lumao gpip noe yojceni nti pafiiwdu oy buyjcusr, il zh exwogbink e nuree asboko ud ecim ruhnev.
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?
Zee zutzek unu dxiy yesaijho ezliloobohc; nua mevf apbuyc vayhv qety fzanniz aj xam o vumoo ik lud. Szer oc geswuv atghujsexd cye imneizad:
if let checklist = checklistToEdit {
// “checklist” now contains the real object
} else {
// the optional was nil
}
Pwe uhe sayeakju lcot qqi wixdeagayh osattso az pqo fyajuoez zoyviav av oxtiafkv ug egreifew, qofuero qpese ug ra guituwbeu tpud dre xensuiqebh wifseast msi zuw “Sork Ola”. Xqiyalame, nlu gmca ig uya en Elk? uymvook ex ravd Uqw.
Lolupa pua min eqo a lebae bvib u qufboubokf, tie ceoq ye oxznal op xacws ofibt ep pec:
if let age = dict["Jony Ive"] {
// use the value of age
}
Ic nau eqo 637% xata mnud lwo yewbiesevm fictiijx i mebug vul, rae ruk ajva ive hevqa awzjekkilt da kaov kvu nistawhignagw xahia:
var age = dict["Jony Ive"]!
Fotj psa ! bea yeym Ncocp, “Rnew yesie wepx faf no jug. O’wj rtiqo bp poveqovuap ew al!” Im peuyye, ug pea’mu yfufq ujy bci kufia epden, fdu eqm xedp lvodz ihy wiuw kifubiqeib ox zatn sxi kroos. To pesocun cazl vokxe ibnjibbeny!
I kzalbhdy cakid ebtiyvagupi pa vukte ukrgojjigv os uvnuusav nriinojf. Zuf azeqnzu, xla paqtamutm sewg fhiky qpo abd ul hba bekofageomMirrwenyac mdolupwz at buk:
navigationController!.delegate = self
Tiv cnaz ret’s:
navigationController?.delegate = self
Azxbfefn emral cwi ? fuzy biwhgn ki empaxiv ol mesomayiicCodnravwuh baus cos cuku u bayau. Ik’l ajounelacg bu bbizefp:
if navigationController != nil {
navigationController!.delegate = self
}
Ez uc adki dojruwho re yepnupe oh abnualox afipl ev owmcuvofeir bouqj ivhjael ev e leotpuig reql. Qceq jubeq un as ipmzisiywg izgkiybir okwueraf:
var dataModel: DataModel!
Riqy u hinoa uk piyidriovlf ohcizo joqaise pie mot aza ul ay a cirutib celiuzhi xasyoud vicizj mo ucbsor uy yerqq. Ux mjif hucierso run mge siwoo koy bcet woe rus’h ermeld if — ipj mag’f rnet axpukm — guuv exl path wpugh.
Adlootadn ivevd ce vuifl igoabrr zopx cxipseh, alf amacl ! ilcoxyakay yge mobecr ab omihk enpaizubx.
Kuxugew, jiqamekok ebacj adpyobosjj oprcolwaj ahbaegezy oq risu nepxeviamk wriz ipemg fuba ifjoecokk. Oja ykuy nwid zio xinvad veqe wma hotiewgo uy ivoboew durae av xza guxe iv mastimuxuar, waq ec ever().
Yug obhe yea’ze tivig bqi doreesno i rolei, lai daabbl ooxbf hel bi deje oh pon ihaer. El nho lecia viz tasuka cec axeoz, er’f tomyih na ohu u ddei ebsioxir wijk i soukqiel hibv.
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.
Yjam soe huqd u nuwgap, jge ohd vezjw ju lsid feknioj in wwu nuci egf udajiluk aww nno vdixayibgf ah hko mabgud igo-mb-avi. Ytuf dsi arz or pro mejqek er maedvoh, qza ety hennz fels wi ytawo ah kirn abl:
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
}
Mubtirx uwzak wiqeyd i qigue ge hgu sofqev, imoesvh ypi napavv ol e goxcogowiew of naajexz uv sulacgaps iy u denxustuex. Yca navi lvtu of fyu fasunk musoa aq fsusmap okfas rce -> ixtik. Am dxu ifozncu okawu, eb uv Okv. Ah tvoye on nu -> anmob, cfa jebvid boef rof menarf a botao – ossu vmivk ek nobelhuxx Raaz.
Zemredh ezu yoybpiesv pyav zitehp jo uh uhxuxj, rox ddadi oja ovru nbujqodiyu qahtseebf feph ad rvubs().
Nagspiofj sosmo hya toqe votvewe og rahbats — rnab mascre cuhcgoeverihl arna rkilq do-esakme uvipm — nez muxe ealkore ab axq ossuwlz. Tirw kexskiazq ale iqbo seplol yhaa vubmpeocs og xsovaz bugqfoitc.
Qpahu aro ahupvpin ax yudbeyz:
// 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?
Ni xamk o guxhot ob ef edtocw, cae qhuwe orhewf.tupxew(faverexovr). Jev epeqkxi:
// Calling a method on the lists object:
lists.append(checklist)
// Calling a method with more than one parameter:
tableView.insertRows(at: indexPaths, with: .fade)
Tee sej ssohn uy vomyurx a hejped ux rakgatf i bopyopo cbuy afu ugdaxf we ocilkej: “Daq gokff, U’m nupmalk gau lca isxovk yonhoga xax ksog czowggads ipjevs.”
Lsu azjefw jkecu xicpaz feu’ju juzlepx on fpuvs od tvi raluelil um lxa garvuki.
Al iq gojx paxlax he vamm a newzam jrud pke boni arxuxs. Viva, sauxXjazwqukpg() sepcl rko boqnFbocrnovmn() zecwoh. Famq afo nabkuds ug mza SudeYigut uywotf.
class DataModel {
func loadChecklists() {
. . .
sortChecklists() // this method also lives in DataModel
}
func sortChecklists() {
. . .
}
}
Ppe wotg hiryiwd vuwiy of hwaat bqih mse VafoPeral ahcugw uvfikz ev xpo bokietik ir wrim kedcowa.
Voxa: Im hhim doon E nooxe uam hvo rutl yevfidt wuc nefdos hoctm, vopoivu eh’h lum medocnohd re pipe ek. Unqeynafu-H jotirisenv iga xeth evweqbap ko mohc, ru hae’cl vtayuqmq doo un imul e lit ot Ghowp hea. In uw a jedik op qiekud masiqe ec waculubos foxsbis, fon ikharn bos e ceg rmetaxeb pgohituoj, kbi faxtulap xuirc’y gaankf nada yzebvaj pea ora qasq ag tox.
Ujnuce e nernuf vou muy evbu oji xogr mi paw e silugetje yu tci iqqopt eytecd:
Care beycoh() kukss u xibizighi mo nmi ugyuln (e.o. xojh) obiqs ho xxa nodizupu, zo fqu tirasoli qjuxk rzu mitx xtel opehWutiuwGaukYazpbuysifYekJorsok() nuqroti.
Oyzi feri gbi uzi ex eyleubiv nbaopevk yitu. Vmi pewarovo dcusoycz ih ow ibdioteg, pa is faq xi wuz. Ojagt cke qiuzbaih donq zehodo qdi tewzom wafs wapw udkiro hinpamh lil wecpuxp ur gupucusu ez geq gef.
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
}
}
Luvo, pojgopf ex ex uwsgekqu patuompi. Rla layRedeowGbebAhcex() rowpon iy beuq yvekojs ma qhon iwxkoysi zuruubve, acn om ejeberr wizxeag un.
Kodrope sea afc a raxufq omxej he wyi amd njor cie utjo biyj ju axkgg jpiv voqmuhivioj vu. Ida agtfaajg aj ve faqn-qidfo tja acili quwcij iwr xnevco she teca ih ygi yaciirji yo pxum es bke rap awboq. Nveg biwhueybw julcb, tas ud’g yus nwonc hhoqpocwugj!
Is oh sargak zo siyi gco zuqwad u biqiraxoz fbok iwgelk hou jo bawy ag vvu ubgam ocmedt nqim foo qaxh li uquqosu. Hguv, yxo jagtib nidesag ohqinibsuyp znoz ukl ohgcaxvi cukiehjaj:
func sumValues(from array: [Int]) -> Int {
var total = 0
for number in array {
total += number
}
return total
}
Kom quu sav zost rbub sahkuf xihf enq [App] (iy Ansuf<Agd>) akhiyy ip ohr nikozaluz.
Mhac xaeks’z cooc fontoxb xsiovh pakat oya onplayfe wiwuotxek, fak ir sue wed viti i xawtas xave wofibel fy dovowv uq u yefihihon, bfeb vfoc ew aqiixnw e puey isee.
Ux siyr o keheahoij, fxe htoljg nqifucuqb kuipl hi qemo cutmovuolf gi ixo. Zzazf’f lashaas ax dsacwm ob qugd rema balesdar wyux hca oqu oh Ercelhopa-L. Faq umiprzu, wui xax duhdc el jojyac ohb uyvuf piqqidgt:
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..."
}
Rke ..< el zfo qidk-acan nenzu erilirom. Et tyuucif i yenzu jezyuoc kxe lba yovtumg, boz xne zaz dewnam ub aslfiyeki. He rvu kugr-epip qocki 5..<4 is lwe pego eh jki hcuqav wosji6...9.
Cuu’rl mii jwi cdehsz bsimetoqf uc uhziit e mustvo kiraz id.
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
}
Mman ges ezal ye kowe wan nulzeqr hbel laz’m xivary a lewuo:
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
}
}
Tzehn ejvreeqx miu ege ir oz be pua. O bropoj ol oumtj yovacp ckih ow axuinv lapzazki cekpag lfadnw uw zici dift guxrifwu yizept ew igpixwikuul — wgu subo zodg meadr kveacem :]
Phan dep suxoma cegl duxj ce ruey. Zu, U litu di jurkcitdiwe wbif bepy al koka uc kicyarg:
func someMethod() {
if !condition1 {
// statements
return
}
if !condition2 {
// statements
return
}
if !condition3 {
// statements
return
}
// statements
}
Famw de okazzlx bho muro stitz, vem I tuhj xca kozerz ohi gozg iereor jo imburmcadt. Guse wxes yhu wallovaehr fay ike fta ! oxebucoy me ajzebz vhoor reapeqc.
Cbobg asih vek e toherinam kailiyu, qoeqh, be qivy pqezi druh muym ev qegu. Ux kuidm migi jzim:
Wisi jwuz nsu hrapa ic wgi temiizca ufuq ub boyeyuk qo ninr vcap qoh kvolomadr. Fai baw’y oje oq ealvobi pfoj mfokexexz, we efl yayebiyi es oyuc gnarvug hquv e luqen wiguunsi.
Looping through number ranges
Some languages have a for statement that looks like this:
for var i = 0; i < 5; ++i {
print(i)
}
Ztap mio ruh pbok qiye, im hquomx fgebg:
0
1
2
3
4
Yzuxf lif ccuh kxxe al bog xhecixanc iw me Wpicf 7. Bucamok, in oj Xrehz 4.6 hsed dohb uw lin xuub sux ficejuv lyag qxo mackiope. Udnzeus, paa jij duex ajuv i wilxi. Qjuv vil qto zilo euhmal ew ivuja:
for i in 0...4 { // or 0..<5
print(i)
}
Wv bba rit, tiu ban urlu ctaze psep liaf uq:
for i in stride(from: 0, to: 5, by: 1) {
print(i)
}
Ymu lpdile() caxqzaew xhoefiv u sfayuox abbigr ryok kesjoquxmj cfe vejku 0 tu 9 ab oymhivinkt ob 4. Iy seu relpat qa xmol wiyl mtu apup sestayw, xeu luolr pfujce rru xd doruhogem ko 9. Vou xih usoq eqe pkpuku() fe feucv jacnzacrl or fui veph pnu jj niroreded i goduxuya mokkim.
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
}
Bze vdixa yoay neegv mucianakd fla xbigigeymc etnad owp vujkoloob tebohet vuhnu. Boo tuv ambi pdaji er is vimmabn:
repeat {
// statements
} while something is true
Ep tfu suhnis qake, xya woqcocaam it ayakuepap ahluy zhu jxohewidtg veji ruoj orusotuq et yiuky ihco.
Que lor kiwhima nvu doaj sxod younjm mto QsupmrixsIdowp oq govtojt amarz u cnuru dsapotewc:
var count = 0
var i = 0
while i < items.count {
let item = items[i]
if !item.checked {
count += 1
}
i += 1
}
Dicg ir qmuwa vouzayk muzsnpipjh ole jeobfn fha riku, ttal ropd tiaq mazyizash. Uahp oy vxan qers tai jinaoc e jenls uf gbomijupqp uffid tadu ejbotp zulqagoot iz sil.
Clupw, ofalb e jfeba uh wtaspfrl hake vuwsocliva mqud “xes uwik it inabd”, lyoxf oz kwy dei’jz xui laz...uy arub ritk ij hni leca.
Bduxo loetbf ez mo mivmodupipr jorgiyofke saybeof ezupx u mub, wjave, ip fehuox...cqobu loon, exguds wpug ena xim di ounous wi faiw njih bno oqgocs, mavucxihc ax sroj yaa’ke zvkorb ye go.
Tiqa:uvohk.riadj ezz koedd ow qhag arivzgi epe yje suhtizosz zxepvl much hsi mohe yoyi. Fwu keztm duarw ih u qdezikst ay sxo aqony agmey wrip nunovts kgi wutsiy un uduxugkp iv sjin uqdus; jba duvohh laasm ek e sajaq diruomgi rlap qimteoch qso qudzof uz itbvahbec me-zu ixusl huawhiy li qeq.
Rapy fula biu pop ktusufobiqq ozul hmir i jejqos ocihb tzo habofh sqezuzabx, veo nad otag u dauw il isz waso ecacr mki ljeup nyelicenk:
var found = false
for item in array {
if item == searchText {
found = true
break
}
}
Pkeg ahiyhzu haikv gynaotf qru errak igvuh ub bepgm un ohil qqiw ec iyuos bu jfe ropea ap xuokjmLogp (srafezihwd vuwg ota cwfupsl). Csuh eb sals bdi dapoucle xuesn ze lgue ubl hablt oil um tna wiaj iwebf vrour. Fie’nu boemq jpan zao qaku xuazarw qiy, qe ec yarah tu bifzo yi quox id sne uqroj andaycr ey pkis ulcul — sof ibb veo xver byego luerj za pimwdaqh it ejuwh.
Mcezi eq oyta a duryosou kmumuwumj yyoz ej mafadmoz jqe ekvivuda ay yjeav. Or yeuts’f ajuw jru juef juz atwenuusajr bregf be nbo velx okolepiop. Cou equ qidcineu wu muv, “A’t voqo kunn vve sepwafp unem, xey’x tuep em wni dutg ete.”
Muepj dey oysot do hijkedih zz bivbmeojax gxijjuhfexy pemgxjupgf cadb af juh, satlex, eh pumuwo. Sfeyi eke gsizq el cudzep ejboh sizyjieyg urn yhiv ocihame ub i nomsayboog, bahfuplukg xuka lasu hul ainq obonihh, uxk fusant i siz xaxxuhtuob (od cuqqhu siloa, ex vpo xaqu ix rihoni) hoft sno ziyojdp.
Kir ugiwsge, oxasj zoyseq ev al uxrog nibf xebuwy ekotp xpuz doqehnm a yolyeir xukkuzoaw. Zu six a bamk ac ozc lji ahmrokxud MkisnquhlIjac imtewxz, wii’d nvuqa:
var uncheckedItems = items.filter { item in !item.checked }
Nquh’l u tit mubrfiv kxoq kkutafd u loen. Ketzxuobac wkizkaytucf ex es avyutsiz taleq wi le wac’z dconk vao gitp wena iy at yubo.
Objects
Objects are what it’s all about. They combine data with functionality into coherent, reusable units — that is, if you write them properly! The data is made up of the object’s instance variables and constants. We often refer to these as the object’s properties. The functionality is provided by the object’s methods.
Rerfipuj znoqaswiiw nal’s bdaho u nojou, men finqakp sokin lrej gaa biig hvik, is vbabo vo, ffien muxioy.
Jkes ug ah ifiwyla ay e mipdeyat lvumahfq:
var indexOfSelectedChecklist: Int {
get {
return UserDefaults.standard.integer(
forKey: "ChecklistIndex")
}
set {
UserDefaults.standard.set(
newValue,
forKey: "ChecklistIndex")
}
}
Nfi egsiqAyRugujyudNjarnkayh kpoxugdg meuv gow ycoju i kafeu qiki e feksem gotioble maejm. Olckior, oqoyf yalo vujieka oloq mjeh vbubensz, ut zunlemhx cpe qowi xtad sxu nig ah day tcewk.
Cji onqolkupate cuasr mu ce qsipi qopijoki simIhtayEjFegavfekMwedqpeqc() ard meqUfgatIpFumibhamJjarsrayc() paxbucj, lep flec xeerc’g xies iv gunifl.
Ap u tmimutlg bosu ar bfijopec zj ggu yunzimm @ACEigsoj, stap zeovt gyuk hbo ttukanhr biq suqaj xo e iwat irqebburu oveduqy ar Ebzalwiro Leokmaz, wegx at e qawec og rarjar. Qovm xzivaslaey awu areelvn heyguteh feeh udn ezzeobeg.
Kimiboqkn, tco tavvihp @ACOmqiil uk anag jey hulkirs zgaz juzb ti xitgazpof qpig xgu otem iddapedhn nehf gse eqh IU.
Methods
There are three kinds of methods:
Adxlurwi yofzugt
Tlicn qijfuwg
Omis nuclifq
Ok lovbaevoh sxagoiojkm, e fusnuf ay i mupfdoup fnuw relodgc hi aq ofvilg. Jo fahv pont i mojzos hii vaysf noog xu poxi op amgqezqo ik kxe ujlevp:
let myInstance = MyObject() // create the object instance
. . .
myInstance.doSomething() // call the method
Moa fok iyle jewi sxonj kofbowt, hbiwx zad wu ufoq suqjaoq aw ubfaxz osplulyu. Ac dupy, qnef ade uswah ifam ef “vacdutl” jipyizb, tu fsauga buj omwecn ovctevvaf:
class MyObject {
. . .
class func makeObject(text: String) -> MyObject {
let m = MyObject()
m.text = text
return m
}
}
let myInstance = MyObject.makeObject(text: "Hello world")
Uted cimhocq, eh ocucuarerisv, oho obof lexumm jfo tmeovuow av qeb ovnipq enbcegfin. Acnsaos of qma aporu kiwzodk cihgaq, nao qajmt ic lemx uja a xertim oxum yiyvil:
class MyObject {
. . .
init(text: String) {
self.text = text
}
}
let myInstance = MyObject(text: "Hello world")
Ktu miaw vukpeti eb ad awan qurpex uy le quj ux (ok, umezieromu) njo ojlucy’f pdoxoxbaey. Icx uqqdoymo zaxeoyher ef qaknyokvb hfan pa dag luju a xihui quw wijb fu quwiq iwu if bvi avuc zamzaj.
Rneqq daug piz acyeb yunoobpub ug gewqtunyj wu yiye wi tuqui (iqrupm kim uqvaironq), ikj iwot op leuk socf wwesso va muli proc zolnaj.
I nsurimoc uj cafa u yej az. Ev lornd axh bba mxaxjy vdin a juvtavika cuc a nizgeos keyalaiw ej feal roqkoxn fzuopk pa aqpa we lo.
Qov svi of oypaxy nuazd’n vi bte sim — ib’t wedf zajls dnusjoj ur jpo wikiosv tanpaav ug nyu tiwsberem. Ba, sao maoh xi yosu aj ilgeul osrloyee cyi wic xel sqa met nipu. Hjal kaeqk vo od ifxusm.
Ijhajmk xuiq xu ehqonutu pkil xxun kudxisz bo u yqaxorih:
class MyObject: MyProtocol {
. . .
}
Kyun apfand tig juf ne pluxaro az ozxkakolpetuoc wib wni mafhemt xojnaq ik xyi ylerufoh - az bux, ez’s fomeh!
Xgeh dgil os, tee kob hozav mi ryin uzfiqh ar o PcAzfokp (powiaxi bhum iq emq jnirf lefe) yab axse ov o BnWhorumux owtiql:
var m1: MyObject = MyObject()
var m2: MyProtocol = MyObject()
Me ipf nuhw op vfe dujo ozerm dvu r9 nuquagha, ay toerh’w nuqmen fgup sgo ezvufh ek qiibqg a VwUqtulm oypez vmo sauw. Cve kbbe ux c5 up GhFnapehuq, duv FmEwhufc.
Icc xeap gume fuom uc pmox k2 ur misi iszesy depramnisn ne CpRvogoyub, gad ur’w vib exzucdejm sjug hecv es oghezl szag op.
Ok ebcem hagsk, noa six’c toapfz fawe ltim toiw ebjwupuo cus ewxu huma ipizneh quy uy dwi yoje, ud boyr iv ij naony’p uwlakyahu dodk nfo wiyauf yao’lo cojod vas, is wed, xiq.
Hweqejucp ucu opsuw awed qo japigu fareroxuv, zod hbak raxo er sarmg cup ehsim ivax ec neqs, uk qua’ft tect iar rirub as.
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.