gpt4 book ai didi

ios - 在快速给出错误时初始化字典数组

转载 作者:行者123 更新时间:2023-11-28 13:07:06 25 4
gpt4 key购买 nike

我在 swift 中遇到了奇怪的行为。我有

let valueOne: [String: String] = [
"title": "May 29th",
"value": "260"
]

let valueTwo = [
"title": "April 24th",
"value": "260"
]

var historyData = [valueOne, valueTwo]

但这给了我一个编译器错误

xxxController.type does not have a member named 'valueOne'

当我尝试的时候

let valueOne: [String: String] = [
"title": "May 29th",
"value": "260"
]

let valueTwo = [
"title": "April 24th",
"value": "260"
]

var historyData = [
[
"title": "May 29th",
"value": "260"
],
[
"title": "April 24th",
"value": "260"
]
]

它工作正常没有错误。此外,当我在 Playground 中尝试这两种代码时,它们都工作正常。

我的问题是我在第一个片段中做错了什么?

最佳答案

假设你这样做:

class xxxController: UIViewController {

let valueOne: [String: String] = [
"title": "May 29th",
"value": "260"
]

let valueTwo = [
"title": "April 24th",
"value": "260"
]

var historyData = [valueOne, valueTwo]

// ....
}

你不能这样做,因为我们不能在 class 声明中引用 instance 属性。

相反,在这种情况下,您应该使它们成为static 属性:

class xxxController: UIViewController {

static let valueOne: [String: String] = [
"title": "May 29th",
"value": "260"
]

static let valueTwo = [
"title": "April 24th",
"value": "260"
]

var historyData = [valueOne, valueTwo]

// ....
}

或者在初始化器中初始化historyData:

class xxxController: UIViewController {

let valueOne: [String: String] = [
"title": "May 29th",
"value": "260"
]

let valueTwo = [
"title": "April 24th",
"value": "260"
]

var historyData:[[String: String]]

required init(coder aDecoder: NSCoder) {
historyData = [valueOne, valueTwo]
super.init(coder: aDecoder)
}

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
historyData = [valueOne, valueTwo]
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}

// ....
}

或将 historyData 设为 [[String: String]]! 并在 viewDidLoad() 中分配给它:

class xxxController: UIViewController {

let valueOne: [String: String] = [
"title": "May 29th",
"value": "260"
]

let valueTwo = [
"title": "April 24th",
"value": "260"
]

var historyData:[[String: String]]!

override func viewDidLoad() {
super.viewDidLoad()
historyData = [valueOne, valueTwo]
}

// ....
}

关于ios - 在快速给出错误时初始化字典数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32377752/

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