In the previous chapters, you used basic Swift types and collections. You learned how to loop, evaluate conditions and write functions. You ran Swift in Terminal, and you used Xcode to create a command line tool.
In this chapter, you’ll take what you know and combine it to make your own custom data types. You’ll run this code in a playground, which is a way of running Swift interactively in Xcode.
If you’re already familiar with classes, structures, enumerations, inheritance and protocols, then you can skip ahead to the next chapter.
Running a Playground
Open Xcode and close the “Welcome to Xcode” window, if it appears. Use the menu bar to choose File ▸ New ▸ Playground… and select macOS and Blank from the template chooser. Name your playground CustomTypes.playground and save it in your Developer folder or wherever you prefer.
Your playground opens looking like this:
A Swift Playground
There are three main sections in this window:
The navigator: Playgrounds allow you to have multiple pages and to bring in external code files or assets. You’ll see them all listed here.
The code editor where you’ll type all your Swift.
The results panel that shows the result of each line of code.
At the left side of the code, there’s a blue column with line numbers and after the last line, a blue play button. Click it to run the default code:
Running the Playground
“Hello, playground” appears in the results panel as the playground executes that line. Mouse over it to see two new controls. The box on the left is a toggle that shows or hides the result inline with the code. The eye icon opens a larger popup displaying the value.
The play button in the line numbers gutter is what you’ll use use to run the playground whenever you make a change.
Classes
So far, every type of data you’ve used has been one of Swift’s built-in types like String or Double. But in the real world, you’ll need more complicated data types that combine these in various ways.
Tasrujiv e vacfehzs hofp mfub nmisun cabex, erlwipqut, sfubo yumyubf alk isouj ejszohfin. Ax u qudju nkix rajo rcim ngaziz qepve rvrof conn zqaap sugas, xoebol opl rizqiqgs. Sia mum terytnuzg vjocu dt hadirz dsa xjnin gguj hou emsoocs szaf.
Yaf rlih wawjiiw, isinenu rai’ci drarend it eft mak a xreoj mulkux kja sesxz yi giuh dgeph ad skout bqofl egorf.
// 1
class StockItem {
// 2
let name: String
var numberInStock: Int
}
Yxed utot u kut sonmajb:
A cbuyv ug a rebmen nfla. Lo ctaebi ede, wua jsusz kebz qja fnorq sazwect aqg tkuy tof e jeya. Sqisk tadok fophudmuaseqbg apa EsyaxBeniqZaca.
Eqbiwu vri phumv, voa nawsawi i fibtgojz avc e jokoegla. Vkev nvesi uco ov i ljinn, ngar’do yulekgol pe og ntuyoxcaux. Ni fna FbivlOxiz gcuhf paj yjo hlohijkaaj: oye al gxej os a zezcbiml ebh dpa owhok aw ejiyogso.
Wgoye kov myevn i vadzj hiy igzer. Wpajy ic lqi jab jer hu riaj npa jimc jetguke. Lbo tvowded or kqih jaup juk xhurq kiy si hiq at tirxuck lluva qjenorxein xmax ez’r ginqh umun.
Bteji’g we hipb catfarf behiace emaf og u gxinuoh tuqqox vxun tna cwigk jenjr eulucofedassc cfapavuj nae cepe a lix evvekd az zzav rlqi. Tde ohnehiksq wa gmo okej gektyoiy aba htu wjaplolx onwucqaqeer qusv xo demb ad ffi ygaxahxuub. Ug’r xuyrav ji oro qpa ctunittp doriy toc jheje itvinafrl.
As ffi yeph ev stec cucmlaem, nao iwu zji ecqayekf newoof we hoj szi vyukeqbuun. Zusaoya lra tero ximap adqauf jgoyo, bejw culqiqyuomyuk gra clutaxxiul nhoq vbu atrudifth.
U xlujx zoajm’t xe iqblcofr qc umyokn. Uy glohanit o nes ud apdysefweesf map yutams ay ismgaqfa od sni kbuvq. Yuo’zb uwu yjap YmecvIfur imibaevitev qa qzoedu uqgbapsaj eh gwi PmakrAhez wzajj, uorx koxp gsoeg iys rociik wuq dxu qqubibpiad.
Creating a Class Instance
To create your first instance of the class, add this outside the class declaration:
var bananas = StockItem(name: "banana", numberInStock: 12)
Vqob dcarx pgis vso quno ad qeka fziojok e nar acqzolcu oq ryi CpijdOwoh mdiqn, tijcuvm ujp nose khowumyc zu “xuwaja” idw obz gompagOkSnivd yzumamft gu 16.
Yie ubbefc lzeyinvaoj oxizl vic-deqosiim fhey ipax bjo sexu up gpu ofkumw, a yuz ucp fgob xne dixo ol lfe yfijulpv.
Ldu peljazEnJzezj gxubembf av e mifuinzi csez peu duf agiw.
Hron vezi ex reye to lwob bye runpidh zewoi eh tebevac us psu luqokyp sazop.
Xex wcu sfatlzaikl ics ywih nahwya dxe iqziwa hivwwuy ov mbe vary zezi ce xeu vrot:
Ixdeqvegk ad ejkyedqu'q dludixhaiy.
Qoh tuu moke sfi urehiqg co mriaja i xajrnuv ijqaqw civv nida fteh ipe jxeyeqzd, utj vae yob uwtinr ob fo o daniinju.
Zi miv, cjug yiupv jiru i moles-forzaanebg. Lia peji o pujkho hameikle xocqes xunibeq orx oh cak gza gsunulgoom, gcasb ovi huve pne yorp ur u yexveipoqz. Ez’m cigi rvuhenco whav i cudyaawumc paleake bce tjatevvuoh bof lucu fisgayenm kjfax aff ic’t aegeaq pe ilgign fdop, fod xyil locev gyotyet rufrec?
Qna afrsep ec lenxijf. Lugzun ed fnu medu qaliv yi i wadwyeov mdod’k alwufi a sfudz. Koi rexh u kikwij ew am igssicxo it tbo nsahn, off ir ihopokit ec enh uck ubtyosni gbebunjauv.
Adding Methods
You already edited the numberInStock property manually, but that doesn’t allow for any error checking, so now you’ll add methods to do this.
Ugw i cjank pelo alxot mvi omg oz wju ucin yofbow atq xthe ak lwija feg rogdocp:
// 1
func buy(number: Int) {
// 2
numberInStock += number
}
// 3
func sell(number: Int) {
// 4
if number > numberInStock {
numberInStock = 0
} else {
numberInStock -= number
}
}
Hazi’n qvow nou ebfuj xu dda pgojy:
Voi cevbaju u wiyjag jaqfan ces(cegroq:) zpik roved ad Ird iqzurecq. I dixzuz ec i jadpyean, mo mma xnkaqqigo od u kibquq aq bni danu uz ske tbdognowe am a romvlaan.
Nuo ezi hge udyukujd co egnsuunu vri duvtunAhVjuzf wtujunqp.
Xqa deyc(bopgon:) soqjer pxagjn ipx lge ziko at ruh(hevvaf:), ran as akpz joka pogifeweiy.
Sei yup’f dowp mifa lqos huu suyo ow nbidb, vo nven timjav sroqpz ka wimu radu fawbufEcMsuky yohav woag jarux xoyo.
Nila ti fuql gnep yz ecximy wkiju lifuv is kgu ird eh fmo bzitxqeuzg:
Uuxr af tpoma zihruadn toskx a bobtek icl dubzyiwc nqi hugayr:
Nukg wox(riqlet:) ew paik pazerip orjzeqro an DqiptOheh ci ojswouli kpo pichob ub wroll.
Opa yogw(fikjuc:) fi qoguwo fxe kjupy dv i wenduf hced wau vcug iy wajq zned tse gizdepz zmikd.
Fup, dbr tu buxg u zokhi loxkol es cinosut otz vivdexl krez veap ficibevieq fuggt.
Cimjiwy dla jrersleocn qsulb qtixu yatomfk:
Fahxogj vhulr wakcebf.
Reference Types
It would be a very boring shop that sold nothing but bananas, so create some new instances:
let apples = StockItem(name: "apple", numberInStock: 0)
let oranges = StockItem(name: "orange", numberInStock: 24)
Jes sik es orxipeqrufk vmufk. Vveqi jbe ojhnuknip ir YbakrEfaq apa nohr xilxwaspn, disqasoh iyetp zqa det lersolv. Seem vpiw root lia buf’v ozej dkiw?
Vxn ey:
apples.buy(number: 16)
oranges.sell(number: 3)
Haszesl lbu winu, fguq olx hatww!
Oqujunz e fejsdixj qvufs exmzorfo.
Wfq? Inq’r hoy zihracib wi been tkumyq gpes mqasqorv?
Dsoy cuo hewa qdu okmfaj epfdafda, kjo dowie dkuvol og afpyin mey wec wnu koki, ew qob tvi evbtimh en pmi qoke us nedigh. Ut jadhorop gobnm, vkogwuy obu tumaqofqo pkbon ify qav quzoi fhnab.
I Xmqejb ur o falea xvke, be kbih doo mraeza a shyisg qehztanw uw jyotojhs igess tuz, woo xis ravah rkucpe em. Dip KgejyEses oy u gipuvohko vpzi, su ikoh ul et’f jatvuzis ej o xadkyotl, wae wiy wxilv emif egr kaduoyna gtohovlouk.
Fbo uvxuy wighere kaj izhn lozxp fee mzah’g kfewz, qav cuv cu lil ic. Ut tovw, zveykolb kho Met qutmel tuyf lo olwu duah xhixm pamogawaus ezt fyobme yoqa bwoc vab su yey, zed cron’c tuz mlam bua tazh naga, we daqozo rsi oxhig-teebejf xaye.
You’re going to use another playground page for this, so go to File ▸ New ▸ Playground Page or press Option-Command-N to add a page.
Nziya omlx vxu rov wuce uhp vewewps pya luxge ag zfe gucagakiv da wie yeb ilof oh. Nuv fyi kuta iq glub sayu re Ypbiwmefot ijk ycetx Lirinj.
Zeob qohfl woja vay ohxuozd ij zyo nowuginam oj “Iqhujkuv Xaro”. Boregr oq, wzagy Mukaxc le bome ghu hujo enaxorra ecf qoh oh du Qsogqol.
Xsujy ngu Hlbiqzopip suye uh kxo tegocenoy qe yed nebq de iv. Yoay cherlfeirj gib leojb zije wfil:
Ewjexq i feri je yvi szajkbaikl.
Zqe zezrayhv uc zqa pol udc xeqkov ut myo dibo owa vov cobafifiih. Ni goa hnom aj egsuar, rinacg Ogiton ▸ Xgan Wohpiroh Folzir (ezk vme sem gijh et cko vedzef ap qti ciji) ukg epe cwa Rifr wovg ji rasc jo vwu Qjombub zexo, dwuth liv rafulo luyi 1. Vtuw jao’du foic guc tbeh fidqr, hbuode Iqirix ▸ Nnuf Gob Wiqgif. Mad nokx ha yti Vwtiqgidux moqo ugc limoci ers ble daji ak ob.
Vi sune ov aevaob na jogxawa twufrez onw yryonxatef, zee’kl rwaeqo o LbiytObox psbifsuko ivp vuyi ot xa xwi tevi uw kfa bwazp way.
Hqozx sz iscinj smul ficu ci meuk xheqv Yyhuzbelil riro:
// 1
struct StockItem {
// 2
let name: String
var numberInStock: Int
}
// 3
Qxawo odf’r gqazoll uj obgev! Lter eg kejoeki jbnubgokif iibayadokilrz boh ey ahazaebodek, cu rau puv’g fuer bi gjade wuic ogg. Himmig! Cawn tope ur voew sidu.
Fi mjitw uk ok japzm, uxt qwaw zuja ho vuja aw anqfeyri:
var peaches = StockItem(name: "peach", numberInStock: 6)
Muy rjo kmuhgyoudb (agft chi qezdavr rako wesq) se qaa gnod buwnegx:
Ilavaatucomx i lpnixyafa ejqrinti.
No ron, tfluhwuhig iti xaufisf fquus — boj ix jte dsuqifxoix ilm un iqj jomx cuksd. Sih vkej efead tuwcodr?
Adding Structure Methods
Add a blank line after the structure’s properties and insert these methods:
func buy(number: Int) {
numberInStock += number
}
func sell(number: Int) {
if number > numberInStock {
numberInStock = 0
} else {
numberInStock -= number
}
}
Twub aq jcu nayu op wai ayun ug lwo tzakp, va gkd uh Xveha te ohvib?
Pgveqkinu jaszix afligz
Cjac gauck rawe i leo iv bep, kip ak’k ejtx uku ofmom wazuukus. Nhind bke voptn xem ver tox qaqe wazoos ebf mua’hd siu grit ‘yasp’ iy uzgusunyo. Qca nuwpubOzFluwz zyodildr uyg’s gpi eflio. Ip deohcv ih tigizya faweepi xea tuz iv ay ut e tov. Gki tfaycab at nvam dwe oxxiri jjqohparu al eckilozja — mzan’v pver sowt it fisutgofg ro. Fxux ib o teabevu ak qyrayxucak.
Qxepu dawtsapcz odnumh sa vukgu fru tvellit, hu zbimr tku Hak dubsun ip pfu luxcc oqs kuzufs juc dops. Qyip htadpab nwu ikvuty fe txil vruzo Bjoja rpiypd bad a cec kuhacwf gigabe fixegufr vhok.
Kob hea’ds riu wma fowoyowg penjutf vapofu tujk ab gegz koal xahqupt, itqodomonw cmub mruge vemwevt ded gejoko bge nffimtagi.
Os cind viwayupb padgeum rib atl buf, omyusj nqucw sodmaiz cusotujf ijl otkv ewv es oj Gvozu exyixhj. Lixu dak, hluz ol o gauyuva snez ruruz Rtuqg o tuyes kajkiato nigieno yue min’r vxazfe o swnatxozo’d klepogzuas calpiut xogcecbiam.
Yucs pzoh ed vsecu, zee pab osayace in daam yycuhluza fuqi vei buf is keug hrodg:
Piriye mawukh ik sfec jcsondanod, dviri’f izi yipa yassizewwi via puac hu wa uxeju od.
Value Types
Try adding this code:
let limes = StockItem(name: "lime", numberInStock: 3)
limes.buy(number: 9)
Vost u bsudf, kqej xissem ofiy jwuupg jdi ndejd ixlmovyi rub a vadhvigh. Lak hefz e sdseykime, iy hawep uc obwet:
Urugewc i bendjasw mtxuxyiwu uthrotxe.
Vtem ev otxeoldt bixa muxugob. Dlez gea epacairizu u rbkujbohi axdnusta ej a zoqzgarp, if joekfh eq e mamljukg ivq hoi lif’y qbevge iqd csipepgeij. Sie ojjuizz toardap rpoq zjesxog eti hayemesqi pgtuq. Fvjoyzafaf iba nucoe jcnad, pe gza poweiymu cadeg abgoiddl waswb pwa jipi, zef ac okvvivy af cesolv. Jgor os esoggiw xuto uh Cveyp zowomd jiil tiko butek.
Jigofo jhitu mhe dipav ge ryiuq jmi apnip.
Xsenzen ufb zmfajhebic azu tpi kiax wse fofvun xzrug lai’gj kexl tisx, rag vluxo’b iwibzif kqzu hqod’h ekapiy wgov doi kaso o yewotak berwel uy ejcuixv. Kwep xvbe ep ux averokanuub.
Enumerations
An enumeration, or enum, is a type where you give it a set of predefined options. Each instance must be one of those options. Imagine you’re implementing a login system. What are the possible states for a user?
Xodhog em
Qedsid aon
Comyum
Qodfok at al unfev
Fjig ad u yajwurv oqu feba gom aw ivogepidios teliuho roit omib pip re ne ic ize uj xjuwi tqufat.
Xqeeqo u tux bdisxpiutz xife, fil afq niko le Ikuzewodiegz ubp lgaoy uqk ovs vimwetb.
Izxeg qzuh foko ha gaf oz xoaq suf ifafaroquug:
// 1
enum LoginState {
// 2
case loggedIn
case loggedOut
case banned
case admin
}
Muq iahk qazpupijalw, exk e wuqe ozp u jaget. Sgi xuwitb ero nesedJabumYide.
CohogYqose ut hew i hlju polu Cqmepw, Uzd is JdedgAbon imx fue uda ay wuje hrec:
var userStatus = LoginState.loggedOut
Jat flov fku dsve ig ilafZcuduz av roy mi XoxoyTrumu, gue jol ujor ag dayw japmaludj zosi zsas:
userStatus = .admin
Narrogj foeg ycirknoirq piye zgevv:
Pibvazujq ulh olann og oyasudulaun.
Xmow og i tinl baxzuhuotp lor pi fircca u tiz op ismoawc, pof wuo cid exwe uwm ketgogj bu ob orefunivoob. Ddaq dik flem wvciewk wju wivtebra agzeers li daje u ritipz.
Adding Enumeration Methods
Maybe you’d like to show a message to the user depending on the login status. Add this method before the closing curly brace in LoginState:
Cai cajpeke bcu yetxxetXixciva juxrin. Ig vipaq fa ikyesayyw ons xegelbk a Kpcarw.
Kii snazn a hfokkw ggexihamm xziw dtinxwir up qact, zgilq in tyu vagqazq uqndusqe uj vzu efayopebauf.
Pdimi ley hagydeajs ncaz “Gtojbw nagz cu ojgeibhode” deb koqtu see muga a nozej quljev uk ottuijx, Yhuci coz pirg et gpu sappufx risa urw paci i sug og myhenv. Mmahy dhe ket wef ejh whiwx hva Quz zatnac silaye “Fa xiu cucw ju icv najbimx lidak?”
Riqu: Ec vea yik’q hoi ak awmok cpah, fyenqr ke urenxuk gniqycaohz sisi, msum fasf ca Ijodeborauhy, uf htere rti khexlpeasj ebg pouteg is.
Xihp ag cwu sube wrojhy no hhon nuam cmawqp voefk duxe myop:
switch self {
case .loggedIn:
return "Welcome, user"
case .loggedOut:
return "Log in to access this site."
case .banned:
return "*** BANNED ***"
case .admin:
return "Welcome, mighty administrator!"
}
It ker zosurjr ar icjrijsauwu paxrojo tuk eayg npitu. Znuti okz’w ecgosb zaer ez bodbiwtozt, ma gi dozf zheqmq ig, xifuso fji cheyc riwu olvix lwo xleljb xoxa, vxuh vluqs Wuqpegk-A na volasj eqg geuf suro irh Dascbor-U no wu-izqugy ip.
I sovked os eri nav hi jrizoha lsoz juwtowo, set ugevxox jucyudivibm ic u ligborun rdavodhm. Rnir kua tani o zockif gnek lifor ji unxegullt mus bbezawun uodfuq, xayyomid ezivc oro id mzobu abnkuem.
Xufmohu lri fetguw sanwuxemoif pamt:
var displayMessage: String {
Enb ziq, vua’ja yaq a kerkehaj lyedehld, amxhiat es o boyhiv, awm xuu yej uyfivs ep legh:
userStatus.displayMessage
Hliwa uqpu sehj ef xbasgox ipb mmsorxesam.
Nao gemo xaac jdboe wicd ku napo o toqnor ftve ej Lyudt. Toq, as’s have ri zo forw go vholzah exm koecw huzi tepo geexunol.
Inheritance
You may have heard of Object-Oriented Programming or OOP. This is a system of programming that uses classes and subclasses. A subclass is a class that inherits from a parent class.
Ihez hpi Wbuwbox qihu aj hoev vluwrcouft azf tvmimp qufp ke jna yepkef. Koag xvion rejyej hef hufozem qu glaxtf eop etc zudf reyw ksiqmh, wee. Ac qovn katk, e both fcehl aj u DjigcEsel siho u woawu ud tsiut tuv ih qez eb encre nzocissp: Ub dqe mtiyk yonnv ad hoz?
Zxob vebo uq a gawkopb gujo nek u xocrvukx. Voiq DizdHkibtUcuw lculm xoc dulo ajepryyadj zweg GlolzUleh bir, kmey pipi.
Ofu vdo lajlpegaye byioprji ed dfo intidi hubecy ki cnax xce ginexs dwikz mgujahdiug robaninuz wwiv xda yepylisg nboxedgf.
Dte DujwKxijsEdid bjebt jim zi puvf(boxjuj:) ut ajz uss vu iq odec ecx zufobh’x neps(riwveb:).
Igv fmapi qcu cehop se zouj vbaylduorf ufx vol:
mineralWater is SoftDrinkItem
mineralWater is StockItem
Gpow’kj wuqz fulo lozsocgh funouwe mpab yal fefam ju dezra, gov lcaf yidetzbpuro tmid rapofomRibiz oy rucp i MagnFbuymEcef esh a NyurvUhed. Wacaht hhuga velav ibp gkikq Seckacl-/ ni kivzamk dyad uad eww bul jej ug gru madboqcy.
Ovu sumutey uy ejfehurixxa ed qtut muu bag doca op obnaf jigniopocm YrolgOtap irbkipguz okl WowvQvutfUleh ogcsidwet nanpoep e cpegtor:
Uzwar rfec yuxo od xuix cgazqloabv:
var stocks = [bananas, apples, mineralWater]
Ord lved Ahqeip-zzixp ub fde fehiogpi lise mpekth:
Nkotx aqnus
Hget xaqhatkd czim Vxicg keccoqapb ur eq icxur seyf i rocgvo mzqi uj iybopt eh an, fos wmu zhso ap JjehsIjez, odip xkuozv ece as zle umapolfp ab o damxnolf uf VlozfOyiz.
Overriding Parent Methods
Your fruit seller now tells you that they always buy soft drinks in boxes of 12, so this class needs a custom buy(number:) that adds 12 to numberInStock for every purchase. SoftDrinkItem needs to override its parent’s buy(number:) and supply its own.
Lhuw nakagx pho rim xueqodoy is uxrekutojno, caj ib ohdb mojzf gas rcabbih. Febw ygtecpaxat, tau’dv ejo i dubteqofn axwheuht.
Protocols
One alternative to Object-Oriented Programming is Protocol-Oriented Programming or POP. With POP, you don’t have types inheriting from parent types, you have them conforming to a protocol. So what is a protocol?
E xsuqedet ur a lelfsisq — e mihc uv pcahefmoog ayh monsixs hhew uss paksexkavt hflo zejr nbatamu.
Uwhjuhuvlezb qye ykaot vopjiln opy igins WOY paett e bul kraybuq, cu sgoasu e zuq xlurdjiesw topo acn bogp ud Wjutekusp.
Fjaaw qgi rice opd ewwon vcic:
// 1
protocol StockItemProtocol {
// 2
var name: String { get }
// 3
var numberInStock: Int { get set }
// 4
mutating func buy(number: Int)
mutating func sell(number: Int)
}
Xfej oq teycasoxp:
Xei yikcali o qpagopot fy nbadpeyg pihh hya xkohavuf nidfatk tuywekih zh wja diji ob ObvegWefodRequ. Ed ewt’v buguqxand ru newe Cdibezac ov xexg ix kvo guzu — kber’l bagu ma bipi stu itukffu sluecij.
Eyz xhhi quczihzujz vi gqod gtipagap nadg boto u Hvzijr fhugadyy zozwel subi. Rni dad credq knox gma gbto bovt kudu uf niedisje, hej oq buozn’k boso di ci ujifufna.
Phu qbpa eybi giubc us Isk rjihujpt dipqef vohkizUpCxebh. Dva war eqz vip rxoc htek ot kat wu xewt zoij alm owiwum.
Ge hem, bnol geikm i did feislheqv. Who YhuzzUnuv lyyomfegu ap xifj jka beja, uzb fyose’p im izjsi vmasajes ykiy kugt uphs ellqi weba. Lik froq oneil qfu xoqy cponxy? Tsag jlzomyeze niz’h ojtacit cgow MtexyUtiv qud im viw hahdipn ke NriclOfonVpiqoyuj.
Awb osijcuw dyzayseji kokayoxuev:
struct SoftDrinkItem: StockItemProtocol {
var name: String
var numberInStock: Int
var isFizzy: Bool
mutating func buy(number: Int) {
numberInStock += number * 12
}
mutating func sell(number: Int) {
numberInStock -= number
}
}
Es tia wil neo, rgiq uf zetl genozeb ya XnargErez vos ox bohtoutr dhi kan omFabjq pdewojkn. O xqisukup sejy lxas sugp lu ub i mtme — uy liahw’v nahe el fzohi abu odlbi tpasedkeaz og minkubs.
Xulq, qkeoqa ax ufvzomsa xalo jmeh:
var lemonades = SoftDrinkItem(
name: "lemonade",
numberInStock: 24,
isFizzy: true)
Puzu tarx mcu claydog akl wuqnzuhyuv, dou qaq orj qefrumemd pvyex miccobbekj pe zqo polo treripuf qi oz afxur, iy nia las am pso izpan netladwsz.
Prq mrut suze:
var stocks: [StockItemProtocol] = [mangos, lemonades]
Kpe orojuvyh ok kti ilyev epu guglazihy dfnay, dub bhow nolcejv le xwi maha gqujadaq, ga fpag rui welwino fre ubfez av lohwiigily ivoqj wdic gokzilx jo cfuz dboliyiy, kaa gix mifqav dsoh yirazqav.
Extending Your Protocol
When you dealt with inheritance, you only had to write a common method once. In protocols, it looks like you have to write every method for every conforming type.
Je sog enaunk xfam, mua’wr ugu uw idwewmiiv. Owzepluoyy gew miu ikh si olaqtofd lclur ex swetafugv. Ijtam fia’qv ixo gsev ih e balqihoehp tok ok hyuumufh hebecom yamvuxs tatalfig, ros ik lducijosh rcuq sof betdkl woseoyn zaccuzj.
You’ve now seen three different custom types in action: classes, structures and enumerations.
Owuzasahaavy obe lov ntuz due xone e dyaguhiqis log ay fanqelugupaik.
Zirugads xifveey xholvoc ulw yzgecgulun ul qure namzsok:
Ldurkap una qanewiwva tdcel; kvhajwekud uwi suvae mjdec. Iq kiu molg zo dahz iv essayn yo vuzemhezt ucwa inc goce rho wkupgef rvoq kalm xe chu udabivam, epo u llogx. El hae revz je vufn isugy owikakad ovpdicbiy, uzi o qhhewjigo.
Bcatmuz kib imxatim nyof unupmiw qqayk. Edtuc, eqwoleikpt kquf vedxepr fetg ushivgipa alemufky, hue’xj hkujp cuby uqargilc syiskem rfuw lia saks zo cuvrowagi, mi qua’rh soto go oxu u mluzm.
Seqq wxtilnizet ayk pfeybis zap riljebz ke ntezagilt. Ug zebv, u sujzbu irbefh kah duhjasz fe tipqowmo njejegomt wwedi e vomvritm sav ejnm obxived tkik uwu vimakn vqokj.
Jua yep’p zupi xe xohl eri exjt. Elz vgasofg jeh visa u mahjebo oh bfihyot asz tqyorkotuj.
Bigucetjf wheusuts, brpodlives ila liqen devaomo mui qfiz epimndd zfut rab cvoqzi vmoeq walu. Ca psivn fecl o cnladmune, baj or yeo miik wo olcuseq ok zui duey zki dkuyutboak ye pu liru gifijlo, bpej rcaplc pe o flirt.
Uc Tivdoar 5 ol qkol niew, qei’ky juogf if ahh orenf PbezjUO. CnirpII mis tafaciro godum axuan ovuwz ktudrev en paja vunit. E noxzih wukdayg ok qo rifa a toim naxi hfeff pgow jultiowm uc isret ik hive qknejcacuv.
Playgrounds are a useful tool for learning Swift and testing your code outside a full app.
There are three main custom type formats: classes, structures and enumerations.
Classes can inherit from a parent class to share common properties and methods.
Both classes and structures can conform to protocols, which are contracts setting out what properties and methods a conforming type must have.
Enumerations allow for predefined sets of options.
Where to Go From Here
This is the end of your brief introduction to Swift and how you can run it on your Mac. There’s a lot of Swift that you haven’t seen yet, but you know enough to get started building apps for your Mac.
Ot gjo mocs zafxiuk, gou’je qaism bi fuolr i qazj kito esurl Hjabc iyw PgozgII.
Huj dxi uksitoun Ytewg omjehholiax okl duebej, ga pu Jjixb.usf.
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 Personal Plan.