我有一个函数,可以根据数据结构的内部条件返回几种不同的类型,因此我返回一个 Any 数组并留下注释解释它可能是什么类型。 (我确信有更好的解决方案,但我不知道它是什么)。这给了我错误
Cannot convert return expression of type '[S]' to return type '[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 }
}
我是否遗漏了数组或协议(protocol)在 Swift 中的工作方式?将 [S]() 转换为! [P]
还允许函数返回,尽管我不确定为什么必须强制转换,因为 S
does 符合 P
.
最佳答案
这与 Brent Simmons 在 this blog post 中讨论的问题相同。有一些有趣的讨论on Twitter关于它;我鼓励您通读对话。
要点是 [S]
和 [Any]
可能具有根本不同的存储/布局,因此它们之间的转换是不平凡的(不一定是在恒定时间内完成)。 map
是解决此问题的一种便捷方法,它明确表明您正在构建一个新数组。
如果是空数组,您可以简单地返回[]
。
关于arrays - 将 Array<Struct> 返回为 Array<Any> 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32685917/