I have an enum with an associated value of struct. When I write this code it compiles without error:
protocol MyProtocol {}
struct MyAssociatedValue: MyProtocol {}
enum MyEnum {
case myCase(MyAssociatedValue)
}
func myEnumClosureMapping() -> (MyAssociatedValue) -> MyEnum {
return MyEnum.myCase
}
But than I added another function like this:
func mySecondEnumClosureMapping() -> (MyProtocol) -> MyEnum {
return MyEnum.myCase
}
Now I get a compiler error saying:
Cannot convert return expression of type '(MyAssociatedValue) -> MyEnum' to return type '(MyProtocol) -> MyEnum'.
MyAssociatedValue struct conforms to MyProtocol protocol so this code should compile without errors. What might be the reason of compiler error?
Tis of typeMyAssociatedValue? It could be any concrete type that conforms toMyProtocol. Let's say we conformedInttoMyProtocol, and calledmyGenericEnumClosureMappingwithTof typeInt(remember, it's the caller that decides the type ofT, not the callee). If your code was allowed, we could then pass anIntto aMyAssociatedValue. - HamishMyProtocolinto the returned function (likeIntif we conformed it), but the associated value is of the specific typeMyAssociatedValue. - Hamishfunc myEnumClosureMapping() -> (MyProtocol) -> MyEnum { return MyEnum.myCase as! (MyProtocol) -> MyEnum }in both cases (generic and above) the compiler works fine. I think the problem is that @Hamish and @gnasher729 pointed, without the cast the compiler doesn't know what you're trying to pass it, can be anything and the type safe property of Swift doesn't allow it - Victor Sigler