How do I specify that a non-generic Swift type should comply to a protocol? -
i'd implement swift method takes in class type, takes instances of classes comply specific protocol. example, in objective-c have method:
- (void)addfilter:(gpuimageoutput<gpuimageinput> *)newfilter; where gpuimageoutput particular class, , gpuimageinput protocol. gpuimageoutput classes comply protocol acceptable inputs method.
however, automatic swift-generated version of above
func addfilter(newfilter: gpuimageoutput!) this removes requirement gpuimageoutput classes comply gpuimageinput protocol, allow non-compliant objects passed in (and crash @ runtime). when attempt define gpuimageoutput<gpuimageinput>, compiler throws error of
cannot specialize non-generic type 'gpuimageoutput'
how such class , protocol specialization in parameter in swift?
is swift must use generics, in way:
given these example declarations of protocol, main class , subclass:
protocol exampleprotocol { func printtest() // classes implements protocol must have method } // empty test class class atestclass { } // child class implements protocol class atestclasschild : atestclass, exampleprotocol { func printtest() { println("hello") } } now, want define method takes input parameters of type atestclass (or child) conforms protocol exampleprotocol. write method declaration this:
func addfilter<t t: atestclass, t: exampleprotocol>(newfilter: t) { println(newfilter) } your method, redefined in swift, should be
func addfilter<t t:gpuimageoutput, t:gpuimageinput>(newfilter:t!) { // ... } edit:
as last comment, example generics on enum
enum optionalvalue<t> { case none case some(t) } var possibleinteger: optionalvalue<int> = .none possibleinteger = .some(100) specialized protocol conformance:
enum optionalvalue<t t:gpuimageoutput, t:gpuimageinput> { case none case some(t) } edit^2:
you can use generics instance variables:
let's have class , instance variable, want instance variable takes values of type atestclass , conforms exampleprotocol
class givemeageneric<t: atestclass t: exampleprotocol> { var agenericvar : t? } then instantiate in way:
var child = atestclasschild() let agen = givemeageneric<atestclasschild>() agen.agenericvar = child if child doesn't conform protocol exampleprotocol, won't compile
Comments
Post a Comment