arrays - 将 Array<Struct> 返回为 Array<Any> 时出错

标签 arrays swift struct protocols

我有一个函数,可以根据数据结构的内部条件返回几种不同的类型,因此我返回一个 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.

I've made a Playground with the issue

最佳答案

这与 Brent Simmons 在 this blog post 中讨论的问题相同。有一些有趣的讨论on Twitter关于它;我鼓励您通读对话。

要点是 [S][Any] 可能具有根本不同的存储/布局,因此它们之间的转换是不平凡的(不一定是在恒定时间内完成)。 map 是解决此问题的一种便捷方法,它明确表明您正在构建一个新数组。

如果是空数组,您可以简单地返回[]

关于arrays - 将 Array<Struct> 返回为 Array<Any> 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32685917/

相关文章:

c# - 使用c#设置excel的缩放大小

ios - Swift 正则表达式查找全部

c - 在循环内动态分配结构

javascript - 如何从中间开始对数组进行排序?

python - Numpy:用相邻元素的平均值替换数组中的每个值

c - 从 C 中的数组打印重复项时出现冗余结果?

ios - 如何使 UILabel 可点击?

ios - 快速函数

从嵌套函数调用结构指针

c - 如何将指向结构数组的指针传递给函数