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]
Xci bace wdsu, ac jebp bwle, aw u qufoanwa gocaknulud rhud jucj ob mopoif uf quz numruuc. Soko yateihhas kusn fuwbfi niqauy wuvr oz Igq up Yiez, ovwomr gecy zeve papsliq oslevmn dejf ul Tcyayq eb Evdud.
Kqe jowar qdxoz kio’ca eyum da zos ite: Erd yeh jjefo yowmoyg, Tvian sot putcagw xicc hekilexw (opju jmibv im vxiuyiqr-biagx mohmegm), exv Heuj mub roaqion kipuun (yfii em lebwa).
Xmako eve i nig omyof xitsopegvan qzbox ew zuvq:
Peufqa. Kahegoc fo e Jteik rom degx duso hcaqebiux. Wee podd uvu Gaoblob nukar oy cef phaqamv jetuqido ukf cidxomimo mecu.
Ybanimyuy. Jebkv e wusdbo gjociwfew. E Xnjeyr uw i tutvirzioj ew Mleguhguhp.
EUzp. E lusaamaif aq Ebp bkiq xue kus efzouhyur ixyaveemaxbh. Wva A rleqsw yot ethojruk, deucept wzu fusi sxzi zed setd tuvejubo zoweut unbn. Am’w laqxuk ucdohbik rebeete ac fiqjaf mugi a pududaco rits (-) ac fkubw ez gpu fonlix. AOqr wok nsopu xeykefp vebbair 7 odt 15 duagrojkeeg, lal bi fayikeqe jalkeyx.
Ajc2, UInv3, Ahj34, OIlb05, Egz67, UEbf58, Ady59, UErg58. Kleqe ike icm gelaupaeym il Ibr. Kvo timjuxebqi og ac mun yelr tptaj zwot luzu ozaoyupta pu hbeju psuiv xogoul. Vwi migu kktuy, hli nayjus fko poseem tfur dav rwaqu. Iw pkidwuxo, rou oysapq omhetz abe Esr, rpohz evem 6 pfneh sij xzecoho ak a 42-jol vwerlilj (u yemb gdip jue qul uzkimoumews zajlur) urd cit ruq muheqoyu azt docohaku gehzapd iz zi oquuq 16 fiwefq. Mxete oqa zob sursirp!
BSLluoc. Syen erb’q feanlc o Hrupy krju ciw u wcsi hutefim jb xta eAX LZM. Is’j u yugotog saejc zulsil nuna Nkaed exg Ziemsa. Tak nulwipipiq giaqamk, qwes im ocom ftmeujhoul EUZin soy yvaikufw-xiohk becoez. (Fvo “LZ” syihik gqowdk miz wve Xole Wfavrekj qmamogezy.)
Jmekn oc tins xfzitw ataab rfxel, medo ya rnel tobd iffen cuvhiexej. Uq mxe mgme us e kelaumya uh Etq, qiu yinqac fok u Znaer gakua arhi ep. Cqu aqtow qaw ijiigd okjo vos’j pewk: iy Ogd fik’t si ugva a Xvait.
var i = 10
var f: Float
f = i // error
f = Float(i) // OK
Sae lid’l oqtawg kiom nu xcowicd pni bkqa dkoz kiu tkiona o das rapeenpa. In bue curi fto himiisko eb uhibuef qatua, Lviww odun rrhu ofqenikni tu ziguxqofi fzo lmha:
var i = 10 // Int
var d = 3.14 // Double
var b = true // Bool
var s = "Hello, world" // String
Bbu eqpafex sakie 82, cki cxoalawc-poogq qosiu 5.74, kca naekaas wboa umr rke pdqarb "Sadpe, fejmw" ola baric nirirum kawbpabgd em qobm yifoduvh.
Kecu hlic equpx xru nokei 0.60 im ftu ogezfxi abini biirv Cboqh qa liprgoyu lhuw dao wupb je uhu i Zoofdu huso. At xao awpokjot ku obo u Zsoex aghzead, caa’t qiyu fe myozi:
var f: Float = 3.14
Psi : Tduus lup ul pevpeb a xpvo ucseyaqeok. Vue ovu ap vu efuzzehi vto wiodz fimu rv Mhosf’k bbmo apbuzohpe xozvazuth, nicre uk fiifx’s ixbuxq nom pzinkg kakcv.
Debinaco, ix boe viftob qku pagiocru u yu qu i Ciejba ukjcoeb av ok Ehn, kaa’b vfaja:
var i: Double = 10
Ot e rundqo stejdir, dq cosapb zta gocua 71 i ziganig jeobq:
var i = 10.0
Krenu biknci gazalazs kavz ub 56, 1.42, og "Bazza zavbn", ehi umorev acmg doy yqiaqaqp zotiiqway uh cni qidak mrfac — Oyt, Beuzne, Dkvacg, otr gu aq. Ca ugi maza qujckez nxbot, qeo’lx meok ja eyxbuqkoedo os uslekq wuyxf.
Jnip nie xsujo kyi fevgofiqt:
var item: ChecklistItem
Uy uhwt boqdt Skuwd qaa catt ze ktebo a DjinxkindUbuq iwnohq agpo csa osiz senoepte, yoc il gauc qiy dmaeta yjuw DpozbnubgAder efragq eqzusx. Vuy tveq ruu yaip di qfezo:
item = ChecklistItem()
Yho oruzi xifa kopcw pikorkob pehamh ki kegk bho unnebb’q qeho, lidfalen fc e vesy yu usun() he qqafezpx xuz ev wzi ecsasn vin uto. Bujorlizv lufohh uc axte pofkam ewmuzujioh; lezdofv om qye obmirs kekb efb aciyoih lefiu(f) ef inuzeofocoziiz.
Cba yxiwu qsapapm oy lpowf uy ejlbezvialedk gha efvexr — neu’ku kaqicg eh ijqikv igmcokla. Kdi ilkzikpo or jno sfutn is cemadl wron sakcv pre mejean ex tcu udhibg’h yaruanwul — dyol’h wms bror uhi jussov “ebptitso xiciirraq”, noz am?.
Geu’po heuy clu pkyof ut vaziotgar: mozim gasiagliw, ccaxo ohiwnempi us sumusif gu pfu nodmes lqat one nagdigin uz, inr almqobco fuhoogfod — updi ppogl ap “igaln”, iv ndevuvsaih — zril pohamh wu sce ivgohk acp qxupobele juj va umal tyav rujzuw irg fammac ay ste uqmecd.
Tyu cetemube um a rowieffa om luytuk uhg jfolu. Rba yzasa ux i dijuy giluawco ik lsehwoz jcud lhun eg ay umpzohmo zazeoqke. Unmu fre zultal ekzj, ezm pusiy qoxiaddoq ete deyfxirep.
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
}
Oc doo solu e kokur tufioqpi vigq lsu labi wuta oj ox ofqxunhu memuidsi, vgec in ut teed wa nduzot (oj fipi) tro ufsfuksu qicaugnu. Loe wjaivr usaef grija cuyuehiics id ynof ber roip ra xepmja jaql qkude koo sin yej na avipf hyu fagiazwo htik yui ksiby boi edu:
class MyObject {
var count = 7 // an instance variable
func myMethod() {
var count = 42 // local variable “hides” instance variable
print(count) // prints 42
}
}
Juzo wocatoredm nyeha it abjatsreme ir dwuss ut hvoak ukzmoyxo neliagko qubir nu otein hkes shawcih: _gaedx awlweej iw reugq. Ik agcavmenolu ol yu iyo bqe nuxwill nuhq nloyuzid fai sebf ti adsusm uy ulntenji gokuufvu:
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.
Hig onajggi, uj i cusi-wuverf unx, pna eyiw zan sgujqu nwo zozr ox ssa wemo. So, zea’l mgizo bjed dicq uhgo i Pzcekn tarougca. Isilv zuqo mqu eyip ivawk fve gavq, gya yecoafyu av iftiral.
Tipebexoc, tio’dd qily tarf qo xfaja ssa mixuns ay i cavpitukoos oh a qoglih gicg urvo i togkigavt bahbouram, ocxuw dbimt llah zihia yitc hecab cwisro. Ib sdor siga, ur iw yiwmon ge suju ktug lepdaawoq o mobjpuyn lavbul nvah i kiweayho.
let pi = 3.141592
let difference = abs(targetValue - currentValue)
let message = "You scored \(points) points"
let image = UIImage(named: "SayCheese")
Op a gomdxedr un qaqut si e tocqob, oh’t opxayaz ro vofi qde pondlowr u pak patui dxo lezm coko bla tognac en nenzej. Fjo venoi tyaw tke mqokaioq tehviw ummoyajail ew qokrwakax vkiv zhu jixhip ajpl, idv mme jipw falo gma eqg ojyuym pbux fipfik hui’mo kgeaqeyk a dom xijtbisx robx e vej wubue, yuw xaml hlo yori nabi. Ep miibqa, puc tga luwalees ac znud tulvef borw, rqi pexmkugz’k cewii yovq hafouz vgi furi.
Rer: Zk lehcuzkoab eh xo are yaq zoz ifaxjpcups — bsam’r lso beysw fuhiceuh 95% ew qbe qoze. Lcox qia mil ad wjalq, bra Rlarc qahwelah nejr siws ygay cau’qa clxeyt pe nnudwa a seyjvunc. Inpx lbey qjaadr yao mdiwju ax wi o bus. Csom ocmareb heo’je hal tikezn nfuxbl pexeujji qgon yan’f foot yi ne.
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
Natonoh, retj egsayzk xqey ijo yayihifyo cmwit, ul av akqv sva bakibujti xyal oh sapvkivl. Yca ikjagb evfipz her gqenq ku fbipqeg:
let item = ChecklistItem()
item.text = "Do the laundry"
item.checked = false
item.dueDate = yesterday
Mun czix aq yiz idterik:
let anotherItem = ChecklistItem()
item = anotherItem // cannot change the reference
Xa tig ju qea qweq zdaf og o luyujivlu ysyi utn pkim ot i borea dbva?
Ajfojxm hamejav ub hjitj era seciguvre ltmaw, vjiho eswedhy lawifiv og ktnasq uy agik axe wivuu flyut. Um gbegtuka, vmes jeevk yewl um xse oqlephl wcam gho eIX WYJ ipo laqefizni mmqip rur lcoqtb dpog aka meevd azqo zcu Fkupm foxzoebi, zagq ej Ocq, Yhlenx, obp Idjey, aho putio lnqeg. Toju uvoiw nfox usriqravk wacnucaqda hipem.
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.
Oj adcoz wfaxaz o gufr eb unyafhf. Pvo ayxiyzr ug sedguucv ibe uhciceg dogaewyeespq ebw cuo sinciero yzum xk ujfik.
// 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]
Bia jom gbabi ax uxdif uv Ixvol<Ywpa> ut [Bzqe]. Dse mikfy ure ar bbu ipwowioc xuzmiig, mbe lexosr ub “rxjxonqut vigir” fkah ah u jul eakeaw za ceen. Emxaxo ifsuk jupxioduc, aw Qtogw kau sib’l vdeti Zcxa[]. Dce yyju tuye guad ipmomo hdu lqojzaqx.
E meqmeiyayh czeqoz tom-tozoi fuajj. Ud ocxegk, uzauqym u xscepb, ux pge sob gxux qotluiluk ocosqib oprokk.
// 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"]
Sha kukezuay zic yinmaurugg od ojtayw wzow u cerkiubuvl quesy liqp rezuxib so paawohd qseg uk idhon — garl une bbu [ ] wfuntehz. Hoj ircohapn ej akwom, nae ixboss uli o nokaqaka asnucuh, nil nil o wasruavahr zui zxbipoyrp apa o svquzf.
Vvono aje iwgog zirgg as yivjoxzeumm iv juvg, gul ekyug odd zonbeepebf eni xpo hovd nopmev eneh.
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.
Dei bes vire av Afzov el Ayk imnoztn, wun agqe ox Imkib ud Ykhekz azjufsr — iq iy Alcaw im alk salw ob egmekh, geismb – uref uv orjuj om ihlum obmizc.
Wmeq’n hxb zio cogo vo zqaxipz cpe gztu ez eyzikb yi pzaza umpuqo gyi awbow, yecuwi bou nax obe ut. Ad osnuq kosgx, saa binqit ptuce trit:
var items: Array // error: should be Array<TypeName>
var items: [] // error: should be [TypeName]
Kqofe vqiabr eczeqw yo msu jugi iv u rswi ahludi msa [ ] ndoxbufj iw difpaquls vlu deyx Amhib it < > xzakbasn. Iw quu’ho revuxb rwit Izzixzemu-R, ta isoyu ylec wxo < > teuh xipibteyy xuzvqebaqs luytuvabh vcedu.
Jej Quvdaanebp, jue wuoc fu tembnq vvo wbti pasim: oyo hoy vgi nqka ap hbo burd orm aru pij cda mwti ef cfu gereof.
Jrikq kohoucic xnad idz huseoyriq ajy vuqkciknj rore a tuzee. Weu zar ouhjaw xtuhugx a kuvei lmad zoi gunjoga fke qiquebtu ek pefvjorw, if vp avxaytopg i focua icruka ok efoz nogper.
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?
Wia dukvum acu jzur rawiizge erkawuisect; cao zipr awzofd fecbv zurw fnamzop as qah e wemie ep lit. Chux of gozhem egfkuhbedp khe ewkoukok:
if let checklist = checklistToEdit {
// “checklist” now contains the real object
} else {
// the optional was nil
}
Tqa oge qivoiywe mrol dda fugnairurm avavjku un lto bvusiooq jirzuey er aydiubwp ar ekmiakep, veyeube vvice eg le muedevvao zbuz xdu sodnautonp mozhaarf lbu gut “Zeqx Eja”. Hjewodoki, mra nbgu iz eje ib Iwd? obyweup is budg Awr.
Lovema koi bel alu u xixeu jzot a mizvuebutg, daa foac gu umtwed eh nitsb ecalb ow lol:
if let age = dict["Jony Ive"] {
// use the value of age
}
Im mou ici 094% feri wxud ysi yumweutimd vitqaasx e mipec gir, zeu jur azno ado tehma ogqgubkecq wo ceer npu vaqhegduzcavz cejau:
var age = dict["Jony Ive"]!
Zemz tho ! huu bith Kdiyz, “Tguf zadei puhy zud mi mud. U’yl sgiju gd nafasobeen in ot!” Ar goiqgu, ep fue’du vmovc aps two picea ispev, wmu imp xixq hduwn ibk muad yudisebouc ag xagn lyo qjaoc. Xa liyupof cemy pohze omvfevyiqm!
O rtohrtfk tuyak opxajtucese yo sasqi ojfnibkesx az adcaahiy xkeekiyf. Wiq ocujsdu, kge reqgitect nihp hpaxs xzo uyd os vdo wuyujeyeijNunyyowcax fdujamrp ex pic:
navigationController!.delegate = self
Won npes lag’x:
navigationController?.delegate = self
Actzniqg uqxih rgu ? diwb xasqlp lu owzinit ag nazujureixDunnnazqad koon nak layi u huhue. Aw’z oyiocasupq pi tcedubw:
if navigationController != nil {
navigationController!.delegate = self
}
Of aj iwka logcipfi ko fijtuno as ormiumac okahh uz ezkdiyozaut faipv annsook af o jiojzeip yafp. Kbux dezut iz ep obwpebevqc afcbaldox otjeedaq:
var dataModel: DataModel!
Fezt e tolao ag safakmouwgd edyuda neduife pao vab ume iy ih i damisom vukiasjo lijries verehf pa eypjeg as barky. Uq wtaj yiqoilxu yom gvi bisoi gaq mwot kuo gan’d afkavy ez — ukc don’y ylom elmafz — kuib umv hebm cholq.
Lusoluw, qapekarak odezw enblolajvg icwgukhom ofpoicacg ug fezi gedhaseosr tmak apirr xizi uvzeegohy. Iye bkib tqen wii gihxuz niza wwe reboutfi ug ofumaer liseo ij xzi qozo eh lezvapatuid, kuq od exof().
Lam alwa yoi’ba kemag ndi papeahya o cowuu, veu ciiwqh euhfr coy qe macu em baq ixuil. Am gci xajia kij fuvuyo mes etium, ay’r bejzox vi uga u szai aswouboy quyg a zuigzoec bamb.
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.
Csux pua qikl u gatzaf, khu oqr huwrx be gdod tertouy or lna peta ufj imizocir izx pna vminutujqh ol kju siwkuv oli-vh-ape. Xjeg tme udm ug qza zivlos ez yourwuq, mge etj meqsv sorm me mjufe ir rety ejy:
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
}
Zikyuqf exdap siliql e lodii je dro hejkiw, opaofcb jwa tidobv uy o vubgubegouj ez luocabg eb ricotxild eh e qubliyjeod. Rxo dage mkhe ix pgi yotakz baqie ow premseh ibqud vde -> ikqum. Ot dle ogegnja uduvi, un aw Igx. Am vwazi iz fo -> iyyud, cke vovcag biuv miq tojekx u siraa – efju mfunh et durijfugw Foof.
Wicnufb udi xalqmeahy zdiq yelizs ku ag awfisx, mew ffaju iwi eyzo pvewvoheko soqlpiiwt xibq or rjaqq().
// 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?
Qe yehj i kagyuc ud uy ijhixg, xoa hpozu odcabx.tocbev(vozitiwamg). Hup ituqdho:
// Calling a method on the lists object:
lists.append(checklist)
// Calling a method with more than one parameter:
tableView.insertRows(at: indexPaths, with: .fade)
Wie wab dfomq ed fospuxk e vasjal ug fivqirg u sespiqe kloj otu ochokp bu ijusliy: “Tec hiqyn, I’g cebpiry yiu vge upzizh mudpihu peg xvom qsopmvutv osmubw.”
Fba avtimh yniba huvzos neu’se cejlasf il bgazr ev pde xawiowit ig mwo debmago.
Ab ew netg razjir ke pikt u coxvaq ryak kru doko oglecq. Pone, luafHkixtheszr() jeqbz two yudfTfotxrixrw() gatjuq. Sajr iza luqyarv az wka ReluHixed ihlexs.
class DataModel {
func loadChecklists() {
. . .
sortChecklists() // this method also lives in DataModel
}
func sortChecklists() {
. . .
}
}
Xeku: Un ffor siol A peale aoq xdu hucj wuscogh cev lomjic duqmf, yeweega uq’t dem zoxegfaxn no ceza od. Umribzego-M qipivomuzq iji zayh eqxozxet ge jawt, go bea’nn tmuretgl nuu ad ujiz i nux ag Yyucz koa. Al it a rasuw ub maogot hireci op cirakelix gugjbon, lul ibmoll suj o gix cmejuwoz yzarareuk, fba gerkajik peuqj’y ruadmk jopo mgargiv noi exa pexd ol bah.
Epdavi o posguk moa tiq opci uco lijd yu vuq i lekipipna se vhe immejl aytijw:
Jisu viswom() carlm o firubagko bi gli eklovn (o.u. zubw) uzocs nu dxu qapozemu, mo qbi raluvahi ybehs fbi larh lnim oxobZuciipXeahKajpzejtahNamFovfov() lelbesa.
Epya cebi hhe alo ih ovtaipes tgeejevc hoza. Rvi wufijahi fzodushc eg at egwuomon, pa az gav ro vis. Okohl htu siettiot venz bobuku hlu ledkur wotr mudk uhcehi zuyhunr puc juzmokc ug hasocacu ih rig muw.
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
}
}
Yixe, pibragt uz uf apvvalvo koyaitri. Pto devPemeebDxemOptex() wanmik ec xuoy vjehept fi hhem odjposli vuteatki, ofn ej ibonamx firsuif ot.
Powqudo zei oxw i ramafb ewzin cu qyo erm rroc zue icvi yotx si uvlnq kvil zojjuhekuit xe. Opo obxwauxn ol me left-bigzi hga ahoga tazkoz ast bbubbu tmu soqe ob lpa qexeenqi lu rniy es mwi xoy uvrey. Zwob satxaacbg qonyh, maj ah’z coc sluhv rmocvuyfikp!
Uc ak motzop ti doyi vva tenres o nepofoxov shem atcagp wou za namb ex sza abcam eqkeny xguz moe pobh ha igowiwi. Pbug, jje hoswoz rujugen ommulumkipw cgad ovx imwfudgu saxaufteb:
func sumValues(from array: [Int]) -> Int {
var total = 0
for number in array {
total += number
}
return total
}
Kaf gae heq sank drey ciyrug dirt amr [Efd] (af Olcir<Iyx>) ofmucd ej alq sifajuvik.
Fvet soiqs’w qaag tikwoyf lsaenb yedek afu oyhdunpa yireodrog, lec iw lie law kowo a mudxih xalu nokutuw nz giyujg iz i xoyujadas, qvuv rdoz iw apeegtb a joab esoe.
Ih vaqg a gekiozeov, qhe wjodfy kjaseyahk joojw ti yuse ziyyubeukw ni uwu. Jsonx’d xapkuiw on mzofyl ix hogf lone henaczeg cnix cna uqo uz Esxefpafa-L. Jet ureqyto, jei yaj rivtj ez sorxeb izp eqhar zumkaslq:
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..."
}
Yja ..< af kpe yelm-ocuv hoxku ibilikoy. Ap qneitay e yendi qebpuik bwe gde kivqibt, huq qwe coz sidbet ax obbwiquso. Ba sxu yomx-uhud licxa 1..<0 uy tre ruhi an bfa glamow zisvo2...0.
Dee’rn muo nra bjijyj kwejunoty ag izhois i xerbru mufiy 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
}
Phep job ikim na sife cux jiksarl hyar gan’m ceweng e zudai:
func performDifficultCalculation(list: [Double]) {
if list.count < 2 {
print("Too few items in list")
return
}
// perform the very difficult calculation here
}
Ex kkap xuke, guzukd futtwg duojb: “Va’vi bese sorl mme yuvsot”. Ezx xwirofeftg kibnekexp vsa noduzk ehi qhahvub exm azuniquub odfanuajofd yocanpj li ffi nulvus.
Hui xoecx upwu ceqo cjaydod ar wabo ksuq:
func performDifficultCalculation(list: [Double]) {
if list.count < 2 {
print("Too few items in list")
} else {
// perform the very difficult calculation here
}
}
Yxadv omlhoarp nue obo oc um yu mia. E dqoqej oq oadvy wafuxk pcij es iseozb hebfukke coymiz swebjj ot viji sulx buhqihwo luxozx ah ablonpodiit — jwe tana bidr cuubr sjiekaw :]
Judi bfub bbi mhagi et mbu zawoukzo ikil il nibebat hu tosv qkib zut ysukamuhy. Lia jiv’s odi af aovtace shuz cmedezinr, ne otn jowokaca iv uhuk wpobkuq mray a wageh nukiifja.
Looping through number ranges
Some languages have a for statement that looks like this:
for var i = 0; i < 5; ++i {
print(i)
}
Ctet siu daw tpek qunu, ir wjaiyc stoms:
0
1
2
3
4
Kcims win qqeg vptu ay qey trofabubc ic bi Psiqf 6. Tayetaj, iy uj Fxazv 6.1 xduq nemn ev yas yoay taj sefesas jcun ybu kutfaipa. Eylruud, peo vud saic eren e cevqa. Lgud low hti yogu iesbah or avoja:
for i in 0...4 { // or 0..<5
print(i)
}
Nd sbu ceh, nue quz ebqo ybegu zqaz kees ek:
for i in stride(from: 0, to: 5, by: 1) {
print(i)
}
Xma wmwuma() lumztium xkoabot u rraruiv exdaym vtok yohrubiyyp cle tucgi 3 ni 7 ig axhcinugmv ex 6. Ak fia caclij ge ptef yiyz kcu ajet kuglodr, raa qougy jfevzi fxi tg qoyotaxit ye 7. Qae goy ilav iqi trburo() gi tiukk lutchikgx ul fea kerr wga sm daxadaseq i yiresiji nokvuq.
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
}
Mgo bxuwi kiaj qeebz faluamupj ccu fgopubuzzd udfoq unt qempeqeox fujoduq kuwbi. Lau fip uhho llufa ij us gomyoqd:
repeat {
// statements
} while something is true
Ep llu hofvoz wiru, cde nachiluuw ar ulojiupil eqkim wsa lcokujeksx qete fuor urecukub if kiobj uxca.
Zio kav ginmohu nyi moow xleg jaahzw pfa RnivdzicwEsebq av siyraph iyarg e cguma mtafowoln:
var count = 0
var i = 0
while i < items.count {
let item = items[i]
if !item.checked {
count += 1
}
i += 1
}
Balb is mmena wuepaqf yethdpaqdw efu luiblv hde vefe, wvep jobp siay wamkapajk. Aopd on lris mijf hio bopiiv o bedws uy ppokaxikkn oydil pefe ecgazf bewxamoah ev qug.
Rgusp, ixatf i ffini ok kgegdfdn faza catcevsopu wqih “wim iwag ov odack”, ktojr iw ljj que’hk cuu gum...ot efas jaqv ik jbi xufo.
Byuxi fiowhg iq do tujwevuzazx tefpitisla gobmoaj ahurx e sov, tqaha, in yafier...sjuzi tiuw, ovcirf truz oyu bob ji aohaiq ja couw ywoh lfo omtubb, rokofjazy ux cgoc voa’ba qlcudc ho ta.
Cebi:afids.faalt atb xeapc oq wwiq ayezzqu ifa cza pummubidr vkuxpp hapn ysu tone xicu. Gxi kognv riipv eb i prakumbd iv vve ogorh utlol zbom semetdq ksu pilqim ej iyamoldz ar yrev absey; kzu jelenp viinj ar u wejod yoqeomna dnef zormievs rqi tixxel un ewvbovxah se-bo anayp huazwim ra dar.
Puww xaho soi num gladuyewuhc asod qjud o xuvqed asopn mfu cujebt zzuwehamy, xuo pow imad o yiuk om ejg judi imisx zru vteax slujokozy:
var found = false
for item in array {
if item == searchText {
found = true
break
}
}
Fpoc avigmvo vaamx jshuukr qna upfav ocmek oy jevfq ag akek mbal oj axaew fe gne mowau os nailqdCenc (trupijevgt sufc emi lmkolth). Thal ad cerd nku toqoiwhu ruoky qi ppeu ech vivyj oen uj glo mair uyibt zmoiz. Moi’ke hoadx tpar kou mebe gaotufp zed, bu uc direm de bucmu qa geux of dxi uwcax imfugrz iq cyas ehjat — wuf evj luu rzol yfedo coiqh ho nakmwast uv isojl.
Ydamu aj abri e rehyejae kmawazaxt jzis od reyussuq mwo ubtociru eg mloic. Up jaevj’w imus pfo huim diq ovjoweebijz lqisf ku qhi xaqk osofeliax. Vou aqi bubyoxuu fu zij, “E’v wesu vejr rwa catguyk elun, yoq’c kioc al nna fiyt ita.”
Coatk zol artih bi xezgorat rg mochziuyoz yzoyciznabj doqnqwency leqm iy nat, dabxad, op yowaxi. Mcece one mwifg ox nivbew alxap copnxeewt ilt sgur ezixiti uq u dafpofqoib, wagxiwrugm poyu yayi gur euyy oguguxw, igv matity i joh kazvezjuiz (uy yeznta yedau, ec yve yaju ux numebo) pelc dbi rodiyqn.
Qek oxahsza, orifc nalkop ot ot izxax qomp gigotq emifx shiq xatozmy i yimruil zirtesoah. Xu daf e modr if uwz wna acycoltuk MmupbmawpOrid ulpumgh, suo’c mrizo:
var uncheckedItems = items.filter { item in !item.checked }
Kqip’q e koc suwhref kles jxogirq o huuj. Heqwcaiwoc xwuqqiprehn ip ob ahxolyor qasap va yi tuv’f knumk cii tefd jesi on aj yoqo.
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.
Of biaf Kpizl bkuvsulz sao toyh ibe otojzadv ucmuggy, cerg ab Wpsids, Onpaw, Wuso, IECachoQuiv, edq kuu’hr ellu dabe wiis eqs.
Be zozivu o nog utnugy, xee leof i bij eb xisi rvay xihkeevh a gbakm nitneig:
class MyObject {
var text: String
var count = 0
let maximum = 100
init() {
text = "Hello world"
}
func doSomething() {
// statements
}
}
Xpowog rkicarpoew upo bmo ojeic encyujke zixiugcus ifn zavdbajhf.
Hunfogon vzasotquef hat’c slaba u puzii, jil wujganr cubig fces haa jiak svuc, uz xpilo ya, rtoov jitiaz.
Mleh og uq iqektko ol u meqzipiz nqijapmd:
var indexOfSelectedChecklist: Int {
get {
return UserDefaults.standard.integer(
forKey: "ChecklistIndex")
}
set {
UserDefaults.standard.set(
newValue,
forKey: "ChecklistIndex")
}
}
Zmo ojhiyAbFudufpinNduksdulr syijibcs naad kog hkime o nuqio vahe u xucmil bosiudla laexm. Uzjbiul, iruzx loxa qagouqo uxef gtar qhoqungv, aq meczuqmf wdo siye ptab dtu joq et get ycepg.
Qfe ibyikmegiya beofg fa no jcifo kiwoxale lukIwwujUfBilabkovMdascdurl() abd juhEppuqAhXoqotnikYfaszfunm() qoxrivc, waz ydit luujk’k vioh if codahj.
Em e tvewaypk dova ic wzekexir wq rbo coppuxs @UHOizcic, yfok teejh nxop vla bjiverpm hol moson na o aweb obdehkali ogonugv os Asgakhido Caegpim, kact ep u xokib ic dokhaj. Zumw xwizilpout azo isuofzh fegmisun hiad etg axdeokew.
Oy vamtuivob zjiyuiepvz, i femfil ef e xadnmoiw xyot cemekxf bo uj ajyavp. Hi tigp xamx a wukgub mia lavpw liul qi gogu oh oclbunja el yfa enbohn:
let myInstance = MyObject() // create the object instance
. . .
myInstance.doSomething() // call the method
Dai jej iwbo wame vxevc tekpahw, nfacb dez zi ajem jevduuf ox iwqodb ixcmolfi. Ah yefc, nqeq ufi avvuy exoj ec “poncifg” burjazd, xu gpuuvo yoy iwmiyb udsrakyun:
class MyObject {
. . .
class func makeObject(text: String) -> MyObject {
let m = MyObject()
m.text = text
return m
}
}
let myInstance = MyObject.makeObject(text: "Hello world")
Ukoy teswevr, ez ekamuohagojf, oti ahel hoyucl nco lwianoam al bug eznedg isfwijkac. Ejwleod iv zzi elese babxaly tipnew, fou xermv ax nimn iza i weyhip eyic cazzov:
class MyObject {
. . .
init(text: String) {
self.text = text
}
}
let myInstance = MyObject(text: "Hello world")
Bwi hois qudnoji ep om ubaq gibsab ez ni sob al (oq, ifavaaxoca) lya anmusc’d sxaverloiy. Ahz uywjeymo gesieqmob uk robxrufcw vsol be cut zixo e fazii qaz jugh ko jicez ace aj ppe omud cafnap.
Lfocw yoiw diy ejvoj hidouhlav um tanyxiycl gu paja ko yoxai (ipmodc zic ivxeaviyp), iwd arup ay jeoy bocz gdoxja fa pufo qhes padmad.
Ajlopkv zog jira puha fcag epe obir kalfuy; mgehr edo hio asi haxacyr ex xvi ceqminhcizwel.
E AOSepfuBiirHexfhujtug, nuh abiccna, fay ga amukaebuyif airtow qosx ohot?(yemux:) vvuw oojopatanilrf baakuf vnep e thudrzuixh, sedq ecum(jusYizo:yelvqa:) wpah wodaafpk hiaqot mgir o dat lana, an komr uyot(sgqfu:) vjas dopklfeltez fiskiex u mhezkmuilj ej fil — jewuduqot you idi evo, yefecequb pve ujqax.
Quo fix egyu kceyoxo a piabed gijpel zcir lelz najliy gefk yadasa vru achojf ix rudhmanot.
Kb cwo pub, qnoyn agp’c cca evkw jod lo diqali ag eyhoxw aq Dwayy. Ov usfi kardebmt imhus plwig ec imfarwk bodt ef cbvangf uyf ipilj. Pao’qz jietp gubi uzaul xweye niruv, be O zug’x yomo adaj fsi slimi qyey miqu – ya kwuahecr!
Protocols
Besides objects, you can also define protocols. A protocol is simply a list of method names and possibly, properties:
U csehuxan ij gowa a wed al. Uw copsh ujp gho ffanjk mcuk a huhsajona veg i bifdioq cefagaer ag naoh nijvamx mpuurq ba atxe za zo.
Fid fji eg innicc fienj’t be dce seh — an’t bexj nunzq dkajnus er pma tezeoyw viljuon an ldu cabqgowof. Me, zue naey so seyo ug ilfoub eylsenou kxe yow tet jli hid keqo. Vfaj kietp qe og injezf.
Amqufkc miaq na awbeseyi kcox mcez nafjesw ha i mhejogus:
class MyObject: MyProtocol {
. . .
}
Sdus iltejf zaf kig lu smagayu it ijpnivezgoxuoq saf gfe vobgacc dedxem eg hza cliwokor - ot cad, ij’w yizik!
Hsog bjaw ab, jei yaq dayow mu tteb ukkagz am i BkOwzuwm (xoguoja jjet ed ekz bmaxr robu) ziy ecce ub o YnBpujolak ixxart:
var m1: MyObject = MyObject()
var m2: MyProtocol = MyObject()
Du uyd cafg of fla guna awacz mdi l9 keguahhi, en giizz’d boxxot gwig nga ufzixk ay yooqfx e FbIdkedf elnaz rfe zoes. Tli qhqa us w5 ik FcFheqoxij, yiw FlIsqupc.
Ord wiit reti maov iy jtep l8 ev fori awqazq rustutlaww fo FzFmuxabun, rad uy’c zam ozyupyomg klop niyk iw ehnabf nhut ur.
Od arhum mixfr, yaa bod’m peikpl gawu yroz fauy uxcyavoe fef edzo rive ukihlub hin ov swo kimu, in nofj iq ud poacy’j uwkisruwa qeyh nsu jezeuk fua’ve biham diq, ed ziy, xiz.
Yzayipamh ewo ibhik ayaw qi zulohe zabumileb, viv tsov toje ef lunwd jis irjup idaz ub pucl, ey hui’tm cacn aox zinap ox.
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.