Reputation: 472
I'm having trouble with returning a class instead of an instance of it which conforms to a protocol. Is that something that's possible to do? Here's an approximation of my code:
public protocol MyProt {
//things
}
var protConformer: MyProt {
return boolVar ? ClassOne : ClassTwo // where both classes conform to MyProt
}
Of course, I get an error here saying "Cannot convert return expression of type 'ClassOne.Type' to return type 'MyProt'
. Any ideas on whether this is possible?
Upvotes: 0
Views: 127
Reputation: 535999
The type MyProt means "an instance of a type that adopts MyProt." If you really mean to manipulate metatypes, the syntax is:
var protConformer: MyProt.Type {
return boolVar ? ClassOne.self : ClassTwo.self
}
But I must warn you, this is almost never the right thing to do. You may be looking for a generic here (in whatever your real-life problem is).
Upvotes: 3
Reputation: 54785
You need to change the type of protConformer
to the meta type of the protocol, namely MyProt.Type
if you want to return a type conforming to the protocol and not an instance of such a type.
var protConformer: MyProt.Type {
return boolVar ? ClassOne.self : ClassTwo.self
}
Upvotes: 3