【发布时间】:2015-09-21 01:01:58
【问题描述】:
我有一个函数可以根据我的数据结构的内部条件返回几种不同的类型,所以我返回一个 Any 数组并留下注释来解释它可能是什么类型。 (我确信有更好的解决方案,但我不知道它是什么)。这给了我错误
无法将类型“[S]”的返回表达式转换为返回类型“[Any]”
S 是一个纯 Swift 结构。我把它归结为一个玩具例子来说明这个问题:
protocol P { } // protocol
struct S: P { } // struct conforming to protocol
// Will Compile: all protocols implicitly conform to Any
func returnAny() -> Any {
return S()
}
// refuses to compile with above error
func returnArrayOfAny() -> [Any] {
return [S]()
}
// oddly enough, this will compile and work
func returnMappedArrayOfAny() -> [Any] {
return [S]().map { $0 }
}
我是否遗漏了数组或协议在 Swift 中的工作方式?转换 [S]() as! [P] 也允许函数返回,尽管我不确定为什么必须强制转换,因为 S 确实 符合 P。
【问题讨论】:
标签: arrays swift struct protocols