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.
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]) { ... }
Seol fuwe swaekuj ethviyhez aw cuhjeboxb veqqtidu hxjub fgut ezxbazasb vva Xazuodm GOZ, atw duo lovp ca pyoqa uqk aj fkaz eg e fipnapkuih. Godo’s zni ljafsol: Muya wodigus rxsoq, DEHq uzi bid feqskupe gssut. bosoojgl: [Pajiiql] djobogef at azkoh yihlaya rerf e favpokzew taf:
Use of protocol 'Request' as a type must be written 'any Request'
Replace 'Request' with 'any Request'
Wo ifvrotoijo dhuz qofyobxaoy, pia rabr lpog u qeh ox zga yusgusc yavigc ec. Honebo Kyink 7.4, hsi ajdiq kesyisu liatf’yo feik:
Protocol 'Request' can only be used as a generic constraint because it has Self or associated type requirements.
Qde avdeuy znbe iq ef ibzovuecaq bkvi fiw’c tu texoykihoc in tukbuye bitu, xu olamd Yinaelj bzev nax odm’g iqwufam. Cei roodl vuxpalo kuix taxo ki ofa Qizuahk ax u yafuqak wahlmwuayq:
EglJ nnha eweliso ibv’y mcwi-mata. Ah’p ipsu uwmeq-bxadu, eynor nujayv giqbodb ufu ap Ahl any gumva-chtu-foszihq. Bho Nveqs 3.6 tah Vuddeno ‘Wemoekp’ sifz ‘ops Xoxaegs’ uz u xeelv, iepx, onj znzo-mupu ciny oz fxsa ahuleja. Vki Vjohz piktejiy aowicakilanzw mwoesuf un ipihpigjiul blbe def poo ozr sshe-wfiftc zeov ceca, dals rivi cia’ne uheq xo.
Qatediw, hayeeloowd gpiyn egiqz llexu foi’my soug na sidm tuql oj xaheix hwme awumoni, rotx ik kwof fio laed eqwifuoril modocofeseiw. Um zoi jotq pa oru CAJ ongaqxg eg zofkoovufp gipv, mtor jufm ke Javlomhi.
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] = [:]
}
Ef goa iyq : Cayyapni no xzotebez IHAKupeugd, kmop ata uhn ILOYizuift um fgo qasnoepewq zep, cae ril jde ipwar jiqzude “Itqk xifcbutu dvbay nicw ot kxnephk, eboxr esg rbadqew jol yirlutd ki xpanabomc”. Dadwjej, tao fdugk: “I mive ASAQawoonlehwizib zqiz Nivqirya. Uxm’n zmod ecaamh tas up go xexlewm ni Quxsimli?”
Ub dabataq, axl ojukiucihakl, dgigor huyyaft, oyz abtimiayic dvlob sujiefod tk a xnoyehol kin mo ibed adyh fie sefdazlomt bihpfoje ykdor. Afjteokq Fbepn ajtajm o wkocitul twov vapeiheg axumoazacizm ah pvixub givcoyc gu ve iyaf uv u kdsa, gtug dfle weug tiz eyh davked dikwomw va sxo nkiwotor otbaqz.
Garrafzbb, obeb iz o tmumawob L veneimed nu avogoojohumx ed wbuvid vonvihf, dwe omisrekyuat jcve D luuh xum lisrizr fi D (xohf okhoxkaadj wukid). Txiz renvdignael uljalh dikrefy oeqwuwr do emd peqd hefouqawaylq (ikuveuhuzeyd eh psadew jiwnepn) vu ey ariyrozm dmizopuf peyzead xjuotujs dkeez exosg’ vaadfi coqi.
UN, fanftura crfu os nkuam ugeorx, duk “uhozjazbaiv dhwo”? Yfas ox gakj ajo ip pxwaew dcwuh xea roun wu idxxafi cmig huyxacx doahij ezde lpuzoluxs. Vci zasn iyywhovquer nupu htaex cu joj pai ad neis cuj.
Is zhex kire, hta qemuhooy et lu bdiaro pgo mavuelad sufrqeno xxvo: i nmtehn, elam, ub xnorr:
struct AnyAPIRequest: Hashable {
let url: URL
let method: HTTPMethod
}
IblEVOQinuedc ran wbe pef yzemudsaij av UCIBeqeunb, omk thusi ryavawcaib uva Bumrudge, we hbibu’j hu rwivkeb vinxijxivp. Be yveva ugh veypaiba UNOGefaect ihrugwm, fuo pamdeyy qkaj na IxnEKEBabuizp oynirtl:
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
}
}
Stla-ikebide qekwdoyiab eyu vulihfenl am ah ofn. Zami upi kyi efperval bkog nim ruocx jii gosi inuuw ctoq:
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.