In Swift's world, if we call the agreement King, then generics can be regarded as the Queen, the so-called mountain not two tigers, when we combine the two to use, it seems to encounter great difficulties. So is there a way to combine these two concepts so that they can become stepping stones in our path, rather than being in the way? The answer is yes, here we will use the powerful feature of type erase (Erasure).
Protocol ' spelldelegate ' can only be used as a generic constraint because it have self or associated type requirements
Because the swift generics do not support contravariance and covariance, there is no real type erasure, and the "type erase" here refers to a class that implements the generic protocol specifically by using a generic generic class (see Anysequence of the System library) for a specific implementation. To solve the problem of variable definitions that cannot be directly used with generic protocols . Specifically, you can read this article
The PPT code looked inconvenient, I simplified a bit:
Protocol Erasable {Associatedtype DataType func foo (arg:datatype)-DataType}Class Anyerasable<erasetype>: erasable {private var Foofunc: (Erasetype), Erasetype init<inject: Erasable> (_ Obj:inject) where Inject.datatype = = Erasetype {foofunc = Obj.foo} func foo (arg:eraset ype), Erasetype {return Foofunc (ARG)}} class Myeraseclass:erasable {func foo (arg:int)-Int { return arg * ten}}class Myerasedel egate<t> {var val:t //var delegate:erasable--Failed to compile Var Delegate:anyerasable<t>? Init (_ Val:t) {
self.val = val} func dosomething (), T {
return (delegate). Foo (arg:val))! }}let test = myerasedelegate (+) test.delegate = anyerasable (Myeraseclass ()) print ("Result: \ (test.dosomething ()) ") //
fuadam1982
Links: HTTPS://WWW.JIANSHU.COM/P/A852865F94FC
Source: Pinterest
The copyright of the book is owned by the author, and any form of reprint should be contacted by the author for authorization and attribution.
"Type erase" in Swift