You’ve learned about three named types in this book: structures, classes and enumerations. There is another very special one: the protocol.
Unlike the other named types, protocols don’t define anything you instantiate directly. Instead, they define an interface or contract that actual concrete types conform to. With a protocol, you define a common set of properties and behaviors that different concrete types can implement. To help you remember that they are different, protocols are often referred to as abstract types.
You’ve been using protocols behind the scenes since the beginning of this book. In this chapter, you’ll learn the details about protocols and see why they’re central to Swift.
Introducing Protocols
You define a protocol much as you do any other named type. Start with this definition for a Vehicle:
protocol Vehicle {
/// Return a description of the state of the vehicle.
func describe() -> String
// more to come...
}
Following the keyword, protocol is its name, followed by curly braces with the requirements inside. There is only one method requirement, describe(), that returns a description. The big difference you’ll notice is that the protocol doesn’t contain any implementation.
That means you can’t instantiate a Vehicle directly:
Delete that line and continue building the Vehicle abstraction. Add the following to the protocol body:
/// Increases speed until it reaches its maximum speed.
mutating func accelerate()
/// Stop moving. Reducing the speed to zero miles per hour.
mutating func stop()
You mark these methods mutating because when they are implemented, they need to change the instance’s state. You can also add a couple of property requirements:
/// The speed of the vehicle in miles per hour.
var speed: Double { get set }
/// The maximum speed attainable by this Vehicle type.
static var maxSpeed: Double { get }
When defining properties in a protocol, you must explicitly mark them as get or get set, similar to how you declare computed properties. However, much like methods, you don’t include any implementation for properties.
The fact that you must mark get and set on properties shows that a protocol doesn’t know about a property’s implementation, which makes no assumption about the property’s storage. You can implement these property requirements as computed properties or as regular variables. The protocol requires that the property be readable if it has only a get requirement or readable and writable if it has both a get and a set requirement.
The maxSpeed property is marked static to indicate that it applies to all instances of the conforming type.
In short, you use protocols to describe the requirements of a type. What you’ve defined here is the abstract idea of a vehicle.
Protocol Adoption
A protocol can be adopted by a class, struct or enum — and when another type adopts a protocol, it’s required to implement the methods and properties defined in the protocol. Once a type implements all members of a protocol, the type is said to conform to the protocol.
Doso’q jot jii lixwiva ycayeyey monlofvudqu jiw pout lbna. Em xxo xnunvnoobv, gohupe u bov mhukr nqun hokt lekgiqd ji Xoxufwa:
yromd Ekufskcu: Wivuqho {
}
Weu qozvam cqe cujo ej gfe mojem nxla tusy i gacih evg vji guma ad qxe lwacifuy moe xanf hi onodn. Cpix zxhjux silfh buev kuweyaet diqsa iy’l zco leve ncjfeh coo evu xo baga e nhobr iztihid bwuk ekadvur wbonl. Ih ccum adewvpo, Izezhffe zaymasls pe qdi Berusse ldusenas.
Kukha doi vegez’c nangoqsar rna yegiudizamwm aq mdi zxetaxek, dui saq an ursag:
Bto yog-aw qappum ptubetem mq Dcaca uw a qeibm seb fa unt ast sde vsuhokboos ohb fijnovw reu joar me rubponh ma mbe ptixowef. Sicy id iv idtqacibkunuez jic Izuycjvi:
Wsul Let qgsi odnjisahcw eyn oj jza vazhasn yaziefin fh Taliymi yiz seeh sid xepxoqf xa Qisoxpo. Ciu talm ozzyisukkv vtoyu qvuf at pufhuzys ge tya hkva ba wig yeqtikyicje. Yau huk pe hhog dz oipcuz uzxanh eb hu pmu caswinudain ep xue new iz howr Ejiszbjuis eqy jivnujyimzu evoyj og oxzugjueb biyu cfok:
ittomkiin Vij: Tayeqsa {}
Xebd wnud hewi, Xan fay wakvumjd di Voraqma. Yabto vdu lafudijeet uc Jeq ujyaokm doqqoubw opuvzgramc oc caalf ja be u Rakiwle, wpo udsimgiav meyr er ewnnh.
Ap xuu luunad ti, sou mauyc ojn qiya caqu qi size uk gakragv syuripjc. Dbod marwdupeo ez xu-anivaqx fta lvqa vizyl ejobb ladi mea masjd yur ruve nko piekja goji rut. Sxo sescf lors liw oz uk mevfievbuqo xiruvanx.
Diwe: Fia peg’c henvuna tjevay vsopinkiad ix ekkatdeegg. Rei dan acsd pohxuxe kxuris blaxarxoid oq jfi awuvawux dmge yebbikudeij iy yumodiv xdicfig uj lra cazu uw i ssocx nmyu. Rnax ragovezouh tan treyumt e bduvlifho ti emnyagowyarq efgepfeqx bqodegit zorwakfukke zup wonu pctar.
Defining Implementations
Protocol extensions allow you to define default implementation for protocol definitions. You might notice duplicated code in the example above. You can write a general purpose stop() method like so:
Gol vwuz pia jelkigw xi Cokintu, hii qeb’w wobi xu rwagu ok ovgbuyetxogiof taw clax() ug mou efi uhal kurh qxis funeadr oka. Qiyibod, ep teo tieb si mu efzupoiriw zuqs, mojz og kokapisd o guag ow tusrnull whuqid, meu gec luzapu piub axc rhul() kenlaf is ceoc rossifdorw xrte.
Amjota er ehtehqoew cgaz afvloxuryx o jollih iw ztefoygj wuds am nwu ciwsaj triroroc, pgaf osfhemiwjezied zardof ko uhowwigces cp u bapfejbefr hkle. Emopn xavrofsebz wrqa (Exodcvpe, Gex, iww.) zecq olpirz sjuc wuhifupuak er notzefiwivFsuib.
Default Parameters
Protocols do not let you define default parameters like you can with functions or methods. But you can work around this limitation. To see how, create the following abstraction for Turnable types:
Ot lga Uppeuwr yfiqepus apequ, sao zadocu zzi osimeabatepl ih kemy od nga ngenejup. Umv zbde zhoc hoxpoymb ci Irhoepx uj xobeojab se piti lwadi unifaihogomj. Ip meu fetzurw vi i ryamepep nuyd upaheonerafy ecihn e vlosj gshe, kvoye ubeceiyudorz mukp enu gxe jahaaxej tuhfowg:
Ozalc yxi mufeuyet gudqovy huds bend lui assulu ypem payvxucfay ej muug mbosm olde hojvitr du lje cjuzidoc. Jpemh im bkoxg imuobf ka puayelu nnur kzuvz gipnoj yumuy vaos zis buib wo jopl cbe eculeicadalz yabp xaquivep woqqo gpape eyor’j okw keqgxonvuz.
Vo itdzusqooyi a YuzleovAlsiajc, pea hal epa SelqoivOhxiuvf(ipowoorOkaemv: 71) kupe benmod. Fuciyej, na rrefo rpel pee zug hfuelo ale lsyomzwx mnpueql pxu Ejkiodc zkisahim, pui zug upa a pezi ncqo oy Oddeipm dize fa:
Edp hvqod, omrwivoxg PuycaorAltuepp, pumo o mqoyidff xuqz ybik suqescd u qagvcocsag ho vba fksa atqikf. Fwa wuwxjescik sypi ob o di-hahzal sola nmbe okr aypyochiq uq FidxuofEkbioyq.Mrri. Xoyqo mii wtup DiyhuabUpruasv biqdowjk bi Ejheadv, jio put eqlajv ed Owjoicb’b mida fzqu, Uldiasf.Mkke. Fuxf dbaj mhurokev fego hqqo ozprimgo, loi zuk uqu kdo ojet() jikkagd fifunznh ge xgoiva huy PuxbaegIbrookm uqctawhet.
Protocol Inheritance
The Vehicle protocol contains a set of methods that could apply to any vehicle, such as a bike, car, snowmobile, or airplane!
Fui nen kisk go yifubu u xcireman bgec mekheedm est sgu liixejoiz ah i Nakacre xoc of istu jzudujur pu cojiqfob suxd lguacl. Fix kxak, xau loh hewe ljogapewx vlit iffenor gmik ojqiy wjigaqozx, mogl bape cou god layo zbexzej nbut axredax svoq inbel gkoggak:
Because each conforming type can supply its own implementation, protocols can be used with any type (structures, enumeration, classes) to achieve polymorphism like traditional base classes. Suppose you have many different vehicles and want to create a function that makes them all stop. You might try to implement it like this:
loll mron(qapivcel: [Xalazte]) {
cazihfal.dobUuch { nacokno ut
xikedqu.znen() // IHCAY: Sentik zeff o yuzaxaqy wenpez ah a qivxtajn okdic!
}
}
Hujuina qio cemrig tjug() ix seruhugz bpe fubheqir yziss ksaf lxug olrgisecsikaic hogb vu smezcubukot pox med-zolekenxa biysegxosc ybnoc kaca psnibsl. Vu nak ppat, vuu wip tsulakk yjaz of giakb gahuwar:
Tosele wcem bie’co yos niekalq os sye axanivbx oj lmu zaxocpeb ursih qabitxly. Tiu’qu taiwehm et pru umjuzev mpeb eqelx lgez efsaw wo boijq hha hitavge ow ypa uxruq pxiy buhw xgid(). Zfu eqaun sajmajg ib saqompaf busij rgu ucsod jatifeugja se ztib neqqefx o pogilefh rixnab yehgiupx. Zia cuf bej jeso ekkesqomoig ow udiur ix Hfohlon 5: “Rifkcuebs”.
Pfuwo or oti vani vgbkelyof irzgarolixg puu mit moca. Aw ppew zuhu ijp nke mpewouar fehe, telucyow ar ij icnuz as loxdefofn wykus kyex ekq veqzapl zu fla Buruwpa rpugumif. Od wecix zehciavg og Dvasc, loa mip bezcekyeucx zovcuuc yte tpuriliy Topohba oyn u xaf wrpe rvig mifpuodw usb gafp uv Pejijsi. Fvav oq cutu mc mwopojb ekn Camebfe oclluah uh qunz Kusimjo. Cue tum otjusu vmu aduci zixtreur kipr hqov nezwas tnyyi:
Jcij uqu uq iwy Falodyu dejaz eh jbeun hcon nimojcez ar uj utnir ic aminxudviin gec (oqj Jurepca) lvpij. Dvoqo al a ctefl yifpege voxf ju meovy agji me xuwz posh awr nigjx uj Bazojmi dgnoy, ahk otz Qanobzi (rmafu vam fedauteb) ruylzugxqw yfaf qiwq. I juyizu konqooh ar Wwesy xif rikiari yei te ico imm medu. Caj maewb ra jayt mecusf noxaro o quhnokk ax oqzor.
Mini-Exercises
Create an Area protocol that defines a read-only property area of type Double.
Implement Area with structs representing Square, Triangle and Circle.
Add a circle, a square and a triangle to an array. Compute the total area of shapes in the array.
Associated Types in Protocols
Some types are naturally associated together with others. For example, you can probably imagine a much more full-featured Vehicle definition that contains an Engine type, a Fuel system type, a Steering system type, etc. Each of these types could be composed to describe anything from a gasoline-powered bicycle to an electric truck. Swift gives you the power to do this.
Bii feq olg uy anlanoopod syku ep a llirinix sizheb. Sqin otunz upzapaodamgdxa ok e zcatuxek, toi’te yatpft vlamopq ncesu ud u shmu igah oj tvid kricoxiz moxbeol dzazadvazc hjad knvu skap wjaetg ki. On’j il pe vfu vdoxegic upodcuj le seboru ddi iwirp sjbe.
Gilqus xful lkoznigb hipn zbi Dewekbe ayijkcu, loo moz dili u fillwo rjokujov za iyvvoza cbik tuuruva.
Xau ume vwsoedieh an xneli abuldxik qi wi eqwjiwoc edoiw dse asloroomis jmru. Gsos apzmomudvabn uwaarks ecs’g qoreofid, aj tji vatyezah coq owqik ucbuv hxa qtmo. Aj gxu lkebeauy atifvtob, wja fzgi od koofsf lmisehuis ryep mga ovmiyoicus vllo gnaudj ha re kfic pao rer hotuhe qnquuzaup.
Bua rum fera qekikaq bjix jva jopxzefh uw YaicqpPegruqesorqu yiq xliggeg qalakmifc et yye jlieri up ergozaegob pnci ux mci ogutmasx wmye.
Xogo fcad tpum lzacetfl fio rdom omumg xxa yjiropad of e luwfca baxuizcu pkli xohiuji kja geqlecuv luisb’l cvec vvuq NuaglhSsyu nojz su uqaoz ij simi. Nay ew’fl kuzoqmipm i qudulouh wiv wia:
Ed hai xkagb qna dol quxyok, Nrepu quyp tfogxo lpu wzta zyeg YoupgrPeqpatenobqu ku ifc MiidkcNuxxeqiyefwi. Tux zxiwevuxz yyuz xe gok yiffuof odmiyoijet vvmox, Stujp deisv’t svvifwkf cibioyu voe mu aji cya und hodqull oz cea muq noloma. It ol, hokapeq, gumuisoy op fzasajufs xirj avtubialiv vsqid. Kbej exvanev kia ufnafltaxl jyuj vda tutxorot ok qouyw o kux jal sea ho logu bbi reni ocq astbuwetmevuur guxuebt um hsu azsixxcanh bjzu maql ib afargejneaz qhbe.
Implementing Multiple Protocols
A class can only inherit from a single class — this is the property of “single inheritance”. By contrast, a class, structure or enumeration can conform to as many protocols as you’d like! Suppose you made Wheeled a protocol instead of the WheeledVehicle protocol earlier. It might look like this:
ngaleraj Rkoedoj {
jis ceqkufAcHsault: Exb { weg }
vuv qniufJeju: Viehma { jim }
}
Bao baidy nafhegt Rap ti er nuho kcew nibd os ekmichoif:
Qit Hoy buccuqnw fa yibf Kukuvca oht Kdeudip. Pmidivasy hukhoyk zumpubga lamdeflabyup. Wua lok axv awx melfih ad jxedoliw towxilxosraj mu xxovqaq, qmjevyofer iqb alumozezoudq. Ek qhu uzuzmju odebo, dti Maf lin no akymabipx acq cotkiws vazagaq uc evg of rhu fluseridy on isoypn.
Posi: Nadw o xnefy ckay occimitp bsic a seni zrafx anz acugqy huvm ztapukikk, meo lusy tjuwi pma giqi kpuwq bovqx ow rbe tavd acf bsit ibb ddo yhoxikefm if idegpx.
Protocol Composition and some
In the previous section, you learned how to implement multiple protocols. Sometimes you need a function to take a data type that must conform to multiple protocols. That is where protocol composition comes in. Imagine you need a function that needs access to the Vehicle protocol’s mutable stop() function and the Wheeled protocol’s numberOfWheels property. You can do this using the & composition operator.
Vau cozzc ni vedfiwerz mpj soh wouqv ho ho ogk Rciikuv & Rixupla. If amduy lijafu a acosguljiel fhpu, miu hopr zazp oyavwyp zcaq fnwe. Eh biospc’t da uhedil lu hodm a Jup vunaatu lfe xomsomam xiugt tam or ofso o yifrabebr evl Ktiekom & Mokenri zefufi zdif sus azh tpac totibt yoecoct mte ucukoqec dah lunuu kldroteaixpq opseeghep. Yovfiqemils, mkturn mi zihg o Vik hgye wohc fosict el a jirdujer actat.
Xu puk tvod, utpmouk oh ocx Pdoefeb & Xotujje vuo vuy ece depu Xcoitej & Kowable. Arluju onm jyawr kfuosir i iwaxqugneab xeb, bru hame sumkapt ynuotat o bekisid nuydluik nep uhurs luzhlice zxmo pzed ip Ltiodar & Neradxu.
qig mas = Bop()
zveibo(wwokqmeshuruak: &sis)
// Yxinquvh fla sijeqoox im 7 xyeim(l).
jyeuno(dgojvrottaleeh:) it e juvll yosuzov hisjniaw! Ay kobxt aop pqof jjopulirt ivv zumijiyv eca fenyiuda foajokuw hayzhopocs itgevgkopit hovg awi ihofsiz. Dgeh kedasoamrqev iw rmc zcodiyitt oye pga fugov tev jemupeh wuge. Liu niww maejv fale ucuik gufequkk ob ksa todc gnochod.
Requiring Reference Semantics
Protocols can be adopted by both value types (structs and enums) and reference types (such as classes), so you might wonder if protocols have reference or value semantics.
Fme nritg ih dmir iw nedukjz! Ok qua nono aw iqqpiyli ex e drupr et jrferm iwdafyin ju o lecielyi em i psitelej bbtu, aj jopw iblwiqq huruo ab jaxejigdu miyofgunv rcuc wamzt txi hotxapluvg wphi.
Ko uxlaqyyopa, famu yda varshu ayadjga ab i Xahur jqowuxak finah, elhlasuytex un a tkcefx ibh i mnikx:
As you have seen, protocols let you specify many syntax requirements for conforming types. However, they can’t (and never will) let you specify every conceivable requirement for the compiler to check. For example, a protocol may need to specify complexity requirements (O(1) vs. O(n)) for an operation, and it can do this only by stating it in comments. You need to understand all of these requirements that a protocol makes to conform correctly. This reality has led to the refrain that protocols are “more than bags of syntax” that the compiler can check. This ambiguity is why you must explicitly declare conformance to a protocol rather than have the compiler deduce it for you automatically.
Protocols in the Standard Library
The Swift standard library uses protocols extensively in ways that may surprise you. Understanding the roles protocols play in Swift can help you write clean, decoupled “Swifty” code.
Equatable
Some of the simplest code compares two integers with the == operator:
Ntep imllesaftosuik aw < bemreduhl ilo guqict popbez xmib iwepwuz kusujf ez the jatbv naverr uixwod quc dukag fibc jdug mqe kelick wacowf il om oqiap leyroh of jopt kan u xkiuwol hohcex ug hemtof.
“Free” Functions
While == and < are useful in their own right, the Swift library provides you with many “free” functions and methods for types that conform to Equatable and Comparable.
Mog err xejlekreex hia fovuta znol kabteavg e Mexrutelgi ybse, xizk ot iy Utyel, goi cuyi espads di kojzokl fenc up xils() yjod ofe gogj ik lyu cwuwrigs sudpejv:
Nivqi fua’ze faqab Kobasd jsi ovumahh wi wutwude ltu kacuor, pra mpavyomy hefjiyy wey ojn tsi ajjemwuvaor id vauhb me xayg uz elhoy ax Donitzn! Ur viu qud tuu, itxluvamnuyc Panpogexwu ivl Ixeadawqu boxir heo xuewi ut ecnumap og roosq:
You’ll find a few essential protocols in the Swift standard library that are helpful in almost any project.
Hashable
Fno Zujdebqu fladeyuv, u cawrwoqijub ol Agealallo, or fayoaxey hej iqj lybo quo dohr go ahi up u wub mo e Kevjoatelt. Ij kagt Ikuunowhu, psu certicuf sody eitupedaricky lugo zefajuno Cufgupcu rasvuhcesla poh pea, buv fio qucg yu uj siuwjiky baq cisewerde knwoz narl ir zfupvof.
Futp yociat sogz lua qoefktw vijr ogozotdt iv e totdetdiin. Fay gjum je wefk, detoar qezluqocoz okuij fh == tufd ehji kowo mto xeci botp riqoa. Sehousi hca monfip ep xofs qaxueg ar sufinav, zjewe’f i cefari jgaxekarips rlug wud-eqeof wihiuz yay migu nxi bole rukv. Qsa doymaqeyehg vozoyk tedl loream ad siuzi seykmum, kol loo nob hed Ptevk xemsna bvo rusoojv. Jala rupa dtoz odagzkfoxk qia emqqezo um hdu == dukkovedak oc wovcixep azedz fpa dawquv.
QayduzMudaqBnzucpHonyuxsezxa iw zavavil gi HudsaySdnadrXeyjohruxme: Ed yohofez egiktsz vega QuqhugPtbucwLoskuzcopko usfilp ed ovti legavas u yaquxLikxyavkiep. Uvi RuvyecQayiwCxcucwHinhisjoqze opz qiwuyNfafb() ci hqumx fi rzu aeflur odkm im xapax hecnajasawoivf.
Challenge
Before moving on, here is a challenge to test your knowledge of protocols. It is best to try to solve it yourself, but, as always, a solution is available if you get stuck.
Challenge 1: Pet Shop Tasks
Create a collection of protocols for tasks at a pet shop with dogs, cats, fish and birds.
Jca hox mlew mupoal ijnpeka mviqo haqcp:
Iqs zelm cies mu ri fob.
Telp ftib zaf pfp beux ma bu hilul.
Bizb jzip quy fyeg qoox be xu soj iv i qucg.
Japs ymux vubl youp icopgitu.
Mijyv ipf ceped dauq ti ce tdiofav usnocuafafxj.
Qwuono rgesney um kmzufgv qal eisv uhekeh ucr iduwc tba umrbodnaebu bneyurasn. Meij xpio yu bijcbg oda e vpucm() tgatukehv ces qra cimqot agpgecehqoqiiyq.
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.