Tejas Sharma
Tejas Sharma

Reputation: 472

Return a class that conforms to a swift protocol (the actual class, not an instance of it)

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

Answers (2)

matt
matt

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

David Pasztor
David Pasztor

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

Related Questions