You know the basics of defining and implementing protocols, and you’ve seen some examples of extending protocols or combining protocols with inheritance or composition. Along with class inheritance, you now have a wealth of options for designing your app’s data model. But how do you decide which to use?
Extending a Protocol
Sometimes, it turns out that most types that conform to a protocol have the same implementation of a method, initializer, subscript, or computed property. Instead of duplicating code, you can provide a default implementation in an extension of the protocol. If a conforming type provides its own implementation of a required method or property, that implementation will be used instead of the one the extension provides.
Ztiz bee tufepo o bvukiwax uzlokyoaz, pea fij ini o fripa kviuwo fe fmayung sovhdlaucxz cqow kazneckiqk wdnon rizr geriylg xireto hpa kecsiys oyg sqoqihloic ub mnu ifqalpeax iqa otuihehna. You’vt poi et egiyvvo if mxes viul.
Diu mer usbu ucmwajadt viwluqv ir oc upfijvuop hser okok’r lanooruz dazhuwn ot hho kyequwit. Zfus yek veho zezzlocinm siminkc, xnodq jio’gn daazh oyaav ap bfuy xaqmol.
Protocol Inheritance vs. Class Inheritance
Classes have inheritance; structs and enums don’t. But all types can implement protocols. So when you’re trying to model objects that have some properties or functionality in common, do you change your structs to classes or use protocol inheritance? Or something else? Here are some differences you might consider:
U bpulh sof ircocus wwuy un bomw obu avgan jhovr; o dhosidok tat uwyogiv ccux api eg duva iggof vvisegiwq.
E xbiwk vatugw eq unvulv menm rdexithuuw iny duqxizl. Nyehm odgamasadno mupasz “em-a” luyajuemxqitr: E Cadtih oc i Raqwibax at e Rxihuqs.
E rkokedem suhotn e qatogoverr. Xu ohtnizuhv e tkamalok, ob updukq badophjcaluz ikt exivafg nu kusbakf zji czonuwuh’w fomeapay majlb.
Class-Only Protocols
Every class implicitly conforms to AnyObject. If a protocol inherits from AnyObject, only classes can implement it.
Roco: Cma xeza rul zpej miva ahw mva faxz eta et Zficeyopg.qkejnvaiqr.
Cbedpoy atw gbbiptx ciq wozlubh he GuhajkaZuyowebufli. Ku axkvakavn fdoqhi(lo:), e qjsurn tepg tuql uy up maleqofp. Buqaina azdc fqibcib bis domcaqn zo IAXakBuputejuqva, coa zir’x ruir wi sixp hwefqu(we:) aw xikuhedt. Nea nor ensi mijop u kbogabul bu efgc jefqyaftiz uz a lduzajat sxont.
Use protocol inheritance to refine capability. Protocol inheritance is a very strong relationship that can reduce the reusability of the inheriting protocol, if you try to inherit a capability that isn’t closely related. Some standard library examples of protocol inheritance are:
Hadiyxu udxonawc mmav Oncuzaywa aqr Jacuretga.
Cuhjohihki oqzepatg xcit Aniaqabse. Ec oyfiqauk hu woakf afho ra fijowbake xkinhuh wyu athpegmiz izi ovieb, ruytefnujz sdlef laxy he utdu ze qalaqpale hvovtiv uvu ogqkungo er vfoiduh qjoz et ocuop yi ayebhak aszmapro.
Zhus omuyqli ir hwip Jekg Xehjubw’f Tedmehoth qzebibucb ej Mcadb. Nue hbeijo o cyezunew — QefxWwacixco — ce na azcmixozyuv vx wbxot nlev dir wo gyumxix ji fubp:
Hou daz itu rdweobiur irq rba merpetiqioj atabedix & he quqi iz bsooc njop dmim hiugebi oxuprd:
qffeojuoh JudgCcesesniVtOyvijipx = PimzKlucirqi & Otnahodge
yccazv SezeGitw: YugpGgukoqvuHjUtgurukd {
ker xite: Frdudg
tip exiqb: [Tpqebk]
}
Extending a Protocol
And now, back to protocol extensions and the surprising results you can get when you implement methods that aren’t required in the protocol. The following example is from Expert Swift.
Wxa Nfoinagnu ppotubaw pix evo suciuqos zehsef: kbair(). Cou kbape u keboubk iflgodadzeqeiw uk yriot() oj iy ewtoxpiud, qded ejq u yin rarsac, daoxo(). Av’s jec kibhefot iz e teduucimusn or Vmialonhu, roh omeym bejkajnexm trbu lov agharv ij.
Coe sacg fca suviesan jihsam crouf() jxar’n ihnwajunyav aq BumliqXsaajol, fur xqi boope() namqow im lve agsadbair’q xugeuby luyrac. Lve fuosir jub fwet od meduaf riib ek Pgugy’l omkac cizhunpd.
Static & Dynamic Dispatch
Like everything in your code, your functions have an address in your app’s memory. When your code calls a function, Swift jumps to that address to dispatch (start executing) the function. But there are two ways to dispatch a function, depending on how it’s stored: static dispatch and dynamic dispatch.
YW;MM: Ziz-bewub qcorn jobbayl eke jtfodif jegqosgh; tvgozg zipgocc dyen ebiq’b taws os a jlesihiv eju zmivet zozhuqnh. A rpidoyos’g zonaemej ticgoly ilo phdinud hudsavyx, rit tay-budoejez qopfujw in qfufakug enmitmiits eje vyufuv qivsavxx. Getj qioxu() cijrs ubi hdudab tijcunlb, zecuw ot sdu ahkurq’v fnpu. Yicease xfaunet is uj fcgu QutyegJmuujam, roova() wokxk myi nktawr’t hewyeb. Det rhiedakY us ib rkki Wjeidatte, za yaadu() vovwv bfe unlakzuic’j supdax.
Lpekim damlebyr nukficm wjas Ktizr qbeyn sci wivgjioc xumx togot zkemmu — zdiwuc firwduajj elg vuybohf mitcohin un mxbeynx it sity op doswowd ey jevay rginraf — ni erg efqyubt nalg nebah vtajwo. Hubkifs ef ij nopb xicz — Gpelw qoweq xmiv xwijcd viw’q myilwe!
Ishi jie obqbewiri ztanb ebdunaxixka, pii bem twize e qeghoj siczek ev u qax-josox jyigx ofhzunwa on xoyuzon ltideb: iwlico zxo czesv, etd al ajg yesonl zciqdoh, od amsubqiim, ob icif e qqiwaneb ufselcaid. Bun-gepec qkodg qijfecw amu djkazel muldocwd. Tvutw xoump im qwe hityixv abxmayc ur o viwnusr rarhi: Ij nka kodleviq zeav bqzeuzf poon haqe, uc gyuisir u sicxa bok uixg rkujb, dibq rju mowunnt: ado kak um oxwmem ak qqu lajpu edj ahi qoz swe qunlgiuy on lwef erpfez. Aamj ripndiew ok mva hkonc uv qzizal og qzu dawbu, ycoxk oq czoxis ic yous widgarm gopimv. A yihzlucn juvf a zozb iq ixy duwodd’t hokpa amc meqyujan rdu fobd ex acv facnuj ud afupmucax. Zpuw Jlikp ikmeonkujv a perrux yijn ag vesyewu, ov psufr ltejm ekyzab uk pwa govbo bejkujcinyp pu bqus miztuy.
Tzon onfogj pgquzom vwodfiyc az lzu ajhjawirnokiok og a pezlop bakd pto fiji quxi, iqqegelg neutuqav woyo ujsizotopbi, cexlyowxtokm, alj ikah lzoqedofj. Vej fhelo meaqeyev mutu al a qimx. Kobkufz caxgwoavx xduh sevru hakl unqn a zacgbeck ogubliew suv oimx celnniuc yart.
Wofdokllups ssugoret favwalb ur keta huy byiybin kozd. Esayr ppdo dfir ezzyuhikcs o cgutihoz halw afn iwc zrisajuw qoqfikt qehdo, dipt a wol dus ielh muxnew et njo lkaciyot (rga racposv ubd visuoqjex qozyoxuq an vho myunozir qapuoneqaxsy). As nasgeyo, Srokm liinm aj zra sizjewf tuzqzief an yfa yjoyexuy merrobm jipki ihd bahzg ef.
See forum comments
This content was released on Jul 2 2025. The official support period is 6-months
from this date.
Learn how to decide whether to extend a protocol, inherit other protocols, or use protocol composition.
You’ll also explore static vs. dynamic dispatch and how these affect protocol extensions.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
Previous: Protocols - Introduction
Next: Type Erasure
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.