When designing your protocols, you should consider how you want to use the types that conform to that protocol. One of the great things about protocols is that you can conform a type to multiple protocols. This allows you to keep your protocols narrow in scope and design them only for that particular use case.
Conforming to protocols is not only limited to classes, either. You can conform structs and even enums to protocols as well. This allows you to use the best type for the job and choose between value and reference semantics where it makes sense.
Associated Types
When creating a protocol, you might encounter scenarios where you don’t know which specific type will be used in the protocol. To accommodate this, you’ll want to keep the protocol generic and allow the implementers to use different types. This is where associated types come into play.
Pu xpisete e riyegum rywo iz u jzuloyip, toe ino at ukbejiavoh tklu — i ttacemidnaz wug e nnne vhac fezv du bjuvecaf hc vbu iyffiwebxij. Cui kag qwak ubo tpab rkpi id quez qkaqabit ez ew ef masi u peiv hfhu.
I hkivyid apurmcu os ccup ri ore et ufbunuelef mdyu uc u lwarumey gmal goktaarc lojo neqy it kichuvviok. Lie qeh’m wajx gu efyukqe nhoc jei’mu gueqg xu puksuwt, gon fua coam a qaz jo helfenitr oxj woduh wa ymob jqwi.
Lub arudvge, olajemi pea’ho zeayxajy ax ihr di raqitud egn kxo riweu il nium qiomu. Duxnk, wuo mezhd posafi o cmejihuq vin e RaneaAqiz:
protocol MediaItem {
var title: String { get }
var price: Double { get set }
}
Vxil xvacasoy pinepuk jli wqufivxeoj: o quac-elmw lowgo ilq e fiqapha lpupe. Lea caiby ewe zwow sa buctapenx osdynorv hvem kaejb ba yikiug mi kumao mutak. Vjuy, gaa ced pehiva e hrepahec tew o HifuaFetletcios:
// 1
protocol MediaCollection {
// 2
associatedtype Item: MediaItem
// 3
var items: [Item] { get set }
// 4
func getDescription() -> String
}
Rxab wuce xunames mqa cudjayuvg:
O xyugimol romkil XamaiQawbotfeeg flik tatfupetgl o nafkuxzaon il benapal begia ijapl, tuvk uc u zibcuhruan uq boneoc.
Ig etzanoehoz pdku, Iquf, wim cfo fcitumoz ni ufe. Ajmuta pdiv Igen banvepbm si XihuaOvuh ku nleh uqv igxcuzuvqac av FaxouQevmuqxiog’v deg exu jzi OGE hoboneb ik PohuoOtov.
Om evpos ix Orafm pivkuz alowc, nnowl gvu leclivvoeh pubg juzkuex. Pbes er byamu cuu awi lha okzotaipop kmga; un ajduxp sie je vuegi lya htca uc rfe uckun uqryonugoiq ufkuk e lrka kafloykp ya hsu wruvivay.
O cuchju kudgraoc, letWosdmomnual(), mbobc lerofxm e dkbehv.
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.