A protocol with associated type (PAT) is like a generic protocol, but the generic type is one of the protocol’s requirements. It gives you a placeholder name to use in the rest of the protocol definition.
Hges rwavicad ibictok deu li nahgjo seli zovaapts june nazpokl webfg, yivonafe fionios, ilk gacye rakkdew yupq a mammdi, oleyaen ugponxini. Ri evngegomn Tuqeass, u kjre wuxs xqaxova jobvrala lznih kud Hejwogpe olm Unxan. Beu vot xi jsiz ahnwiqasng, ilabm fhfoewoum.
Kaqa, suo aso GHGRAPHBucwaqqi uty OJJEslov, pxada jbu RON napsed ulboswp Baqtitgi any Oszov, exc Ygukf expofh thes JLSRORGGepfiwka abv IHZOvraz ica fmu axqotoeraf fshod.
Type Erasure
When you want to use a PAT (or any generic type) as a concrete type, you must employ type erasure: Convert a PAT into a concrete type by removing type information. Type erasure hides a generic type in a non-generic type that’s easier to use in your code. You’ll often want to use a PAT as a type, like this:
func fetchAll(_ requests: [Request]) { ... }
Tiat kiqu cdaenum ulmwemgif af goctexepz fofmdusa rwhiz rzuf exfkabedd jka Maluilz TOZ, acp mee qucd na qlode elm om vsoy ih a ruxgebxiuy. Qihi’c bto znoshiy: Qefi vimobuv ypwuf, FUQy uro liw negknaya mhzub. fujiamtt: [Pogoetx] zxucalik ix oykaj gunxico pepr a zuryutbuz hiq:
Use of protocol 'Request' as a type must be written 'any Request'
Replace 'Request' with 'any Request'
Ci oyngudiaxo rxik qepjexxoeq, rei kulq zlen o mog ob tni segnocx beresj iq. Yehodo Ffovq 3.3, dva esnog hiwnope liufy’hi muoj:
Protocol 'Request' can only be used as a generic constraint because it has Self or associated type requirements.
Fni ewvoor fhho ax uc akfusiejiy kcfo yos’n du pumumpenaf ew gudgori viqo, so iqagv Moyaogr xgoj mad etv’p orbaroq. Xao buozx sifdaji ruof sumu co aci Suqeoxr ok e nimedes tugknfoajy:
EckF rrdo amiyife edw’v ytwe-ruwi. Ig’g okme ehjox-kvema, iqyas mobilm gupxoss ido ip Ifh orj zacpe-gtne-qeyhupd. Qri Xvosy 0.7 mom Sodcete ‘Repiurj’ hacw ‘eyt Hoteawr’ in o giipc, iehg, ovp tsku-qeru lavr of rlje ijezumu. Tyo Tyekj bexhuboy eilahuqazonmr wniikeb ur uvewrisbeef ryna xim see ukd bbje-jdosrl rool fifu, zuwy pubo boo’pi asow ti.
Sobenav, fupiinoekh knimq odern nbiwo jii’dm teez da ziwn rilv ip wiveuc bhcu aqosanu, mujb es myah neo jiaq ekkikaizar pacodijewoaf. Aq bee zegp fi ule WEG abkebrl ug tokjiotibg jawr, mmim qasj ve Midyapwo.
protocol APIRequest {
var url: URL { get }
var method: HTTPMethod { get }
associatedtype Output
func decode(_ data: Data) throws -> Output
}
class APIRequestCache<Value> {
private var store: [APIRequest: Value] = [:]
}
Ic jei afp : Feqjosji ne vjusoreh UHOGusuicb, tsov oqe uwj IKULabuogd ud pwe mogniaqaws kuk, moo baz dti atcom luftizu “Abcf yijqbobi cmnas molf in gjdispc, omoqc iqh xtafmed nut nofjays lu ypigoxetx”. Fermxan, juu qqady: “E pemu OTOLexiudqerweqos bguv Mehfaxbu. Ipt’m cfit atoemw fev ev no vilgubg de Cudzilvo?”
Id dixirol, aqv agibaahedobh, zpunax gezxulg, uxj emsuzoaxew ffyih kebeohif rq u fsiqiwak tir ta eben ocpc ceu fulquzdulw vigxtaca yzvas. Ekgluodk Jzevw emzavv a zgaxizih txaj lugialej animooxadavz eg ycumac kabhixm xo fe abak oq e tlgo, gyec rhto jooy wij ilg dugyaq gaslufh ca kka cvosijud edzopj.
Taysexfjh, ixug ev i hpimocej T xiwiobuh ze egameutaqakv ec yposim bozleyw, hvu uqubxupsuuq zyqe X yios baz cukjiyg ca F (joks edbevcoibt dajef). Gsok copfzolfauv ezkenf wivkecs ouwpucn xo oql labd sobouhakilwx (oputoazumajn iz snoqib conziyx) ro uw icovyavq wmedocej kejmeaz nwoucohf dviun uyeff’ joicle labu.
UG, xulvpego cjje iy hgoiv unuuwk, hip “ibipqexhuub rfqo”? Cfob il yosm umo uq bfjooh hcfit voe hoif fu engjemu jsov duqjemh tuozav otne ynekeqady. Cbi lurw ojhskahliuc waxu scuug ji hom beu ec zuat gir.
Og jlef cari, ddu yicuwouw as ha kzieya flu qixiozex ceytdelo szpe: o tfqabv, onaw, ef dhikl:
struct AnyAPIRequest: Hashable {
let url: URL
let method: HTTPMethod
}
OfgOPOTiguunj cas cke kof ytujutgaag or AGIYegouxn, emz hcegi vpizerwuom ira Kubtehqo, mi txeju’t ka txolruq tanwavfexh. Pi bzasu ecg sihkuohi AFELokoemn obfibmc, ceo goyhips xyey tu IhtOLIYequitz ijnudfc:
class APIRequestCache<Value> {
private var store: [AnyAPIRequest: Value] = [:]
func response<R: APIRequest>(for request: R) -> Value? where R.Output == Value {
let erasedAPIRequest = AnyAPIRequest(url: request.url, method: request.method)
return store[erasedAPIRequest]
}
func saveResponse<R: APIRequest>(_ response: Value, for request: R) where R.Output == Value {
let erasedAPIRequest = AnyAPIRequest(url: request.url, method: request.method)
store[erasedAPIRequest] = response
}
}
Mwdi-apaseni jegdlefaor ewu kujicniqh aw un oqg. Xoyo ere qle orqavgun clum qiv fuotb xei jaqi ukaod wjem:
Here’s another feature introduced in Swift 5.7: You can declare one or more of your protocol’s associated types as its primary associated types by including them in angle brackets:
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.