gpt4 book ai didi

arrays - 将 Array 作为 Array 返回时出错

转载 作者:可可西里 更新时间:2023-11-01 01:04:36 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com