草庐IT

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

coder 2023-09-16 原文

我有一个枚举,其关联值为结构。当我编写这段代码时,它编译没有错误:

protocol MyProtocol {}

struct MyAssociatedValue: MyProtocol {}

enum MyEnum {
    case myCase(MyAssociatedValue)
}

func myEnumClosureMapping() -> (MyAssociatedValue) -> MyEnum {
    return MyEnum.myCase
}

但是我添加了另一个这样的函数:

func mySecondEnumClosureMapping() -> (MyProtocol) -> MyEnum {
    return MyEnum.myCase
}

现在我得到一个编译器错误提示: 无法将类型“(MyAssociatedValue) -> MyEnum”的返回表达式转换为返回类型“(MyProtocol) -> MyEnum”

MyAssociatedValue 结构符合 MyProtocol 协议(protocol),因此这段代码应该可以正确编译。编译错误可能是什么原因?

最佳答案

不,它不应该编译。编译器需要一个可以将支持 MyProtocol 协议(protocol)的任何映射到 MyEnum 的闭包。您给它一个只能将 MyAssociatedValue 映射到 MyEnum 的闭包。如果使用不是 MyAssociatedValue 的 MyProtocol 调用该闭包,则调用将崩溃,因此这是不允许的。

关于 swift 3 : Converting enum case with associated value to closure with protocol parameter results in a compiler error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40271932/

有关swift 3 : Converting enum case with associated value to closure with protocol parameter results in a compiler error的更多相关文章

随机推荐