Ceyhun Ozugur Ceyhun Ozugur - 1 month ago 12
Swift Question

Swift 3: Converting enum case with associated value to closure with protocol parameter results in a compiler error

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?

Answer

No, it shouldn't compile. The compiler expects a closure that can map anything supporting the MyProtocol protocol to a MyEnum. You are giving it a closure that can only map MyAssociatedValue to a MyEnum. If that closure was called with a MyProtocol that isn't a MyAssociatedValue, then the call would crash, therefore it isn't allowed.