I have a generic function where I am passing protocol
type and based on the passed type I am returning a required struct
. If I put a protocol constraint on the generic even if the passed protocol conforms to it I am getting an error.
protocol BaseProtocol {}
protocol ProtocolA: BaseProtocol {}
protocol ProtocolB: BaseProtocol {}
struct StructA: ProtocolA {}
struct StructB: ProtocolB {}
When I define my function with a constraint like this:
func getStruct<T: BaseProtocol>(type: T.Type) -> T {
switch type {
case is ProtocolA.Protocol:
return StructA() as! T
case is ProtocolB.Protocol:
return StructB() as! T
default:
fatalError("Unknown Type")
}
}
let result = getStruct(type: ProtocolA.self)
print(type(of: result))
It does not work and generates the following error:
If I remove the BaseProtocol constraint all works fine:
func getStruct<T: Any>(type: T.Type) -> T {
switch type {
case is ProtocolA.Protocol:
return StructA() as! T
case is ProtocolB.Protocol:
return StructB() as! T
default:
fatalError("Unknown Type")
}
}
Is there any other way to put that constraint? Am I doing something wrong here?