gpt4 book ai didi

swift - 嵌套数组 - 不明确

转载 作者:搜寻专家 更新时间:2023-11-01 06:46:17 25 4
gpt4 key购买 nike

尝试创建下面的数组时,出现以下错误:

type of expression is ambiguous without more context

在 Swift 中可以使用这样的数组吗?如果是,它是如何声明的?

var jobArray = [
["Dog Walker", "Job Description", ["Monday", "Wednesday", "Friday"], "7"],
["Babysitter", "Job Description", ["Tuesday", "Wednesday"], "15"],
["Leaves Raker", "Job Description", ["Sunday", ""], "10"]
]

最佳答案

我猜你在 playground 中没有导入 Foundation 或类似的东西:

// uncommenting the below line fixes the problem
// import Foundation

// with it commented out,
var jobArray = [
["Dog Walker", "Job Description", ["Monday", "Wednesday", "Friday"], "7"],
["Babysitter", "Job Description", ["Tuesday", "Wednesday"], "15"],
["Leaves Raker", "Job Description", ["Sunday", ""], "10"]
]

没有它你会得到两个错误:

error: '_' is not convertible to 'StringLiteralConvertible'
["Dog Walker", "Job Description", ["Monday", "Wednesday", "Friday"], "7"],
^~~~~~~~~~~~~~~~~
error: type of expression is ambiguous without more context

第一个更重要。第二个是Swift上去回家的神器。

为什么?因为 [jobArray] 的类型是什么? Swift 标准库中没有符合此定义的类型——您需要一个 [[Something]],其中 Something 符合 StringLiteralConvertible(对于 "Dog Walker")和 ArrayLiteralConvertible(对于 ["Sunday", ""])。没有一个。

可悲的是,恕我直言,非常可悲的是,这样的事情Foundation 中定义的。这就是为什么它会在您添加导入时进行编译。

我强烈建议,不要像这样定义这个数组,而是实现一个简单的 struct:

struct Job {
let jobDescription: String
let days: [String] // or even an enum for the days of the week
let hourlyPay: Double
}

var jobArray = [
Job(jobDescription: "Dog Walker", days: ["Monday", "Wednesday", "Friday"], hourlyPay: 7),
Job(jobDescription: "Babysitter", days: ["Tuesday", "Wednesday"], hourlyPay: 15),
// etc
]

关于swift - 嵌套数组 - 不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30406668/

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