简体   繁体   中英

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?

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
}

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM