作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我有一个函数可以根据我的数据结构的内部条件返回几种不同的类型,所以我返回一个 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
确实符合 P
.
最佳答案
这与 Brent Simmons 在 this blog post 中讨论的问题相同.有一些有趣的讨论on Twitter关于它;我鼓励您通读对话。
要点是 [S]
和 [Any]
可能具有根本不同的存储/布局,因此它们之间的转换很重要(不一定是在恒定时间内完成)。 map
是一种解决此问题的简便方法,它明确表示您正在构建一个新数组。
在空数组的情况下,您可以简单地返回[]
。
关于arrays - 将 Array<Struct> 作为 Array<Any> 返回时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32685917/
我是一名优秀的程序员,十分优秀!