我正迅速地遇到怪异的行为。我有
let valueOne: [String: String] = [
"title": "May 29th",
"value": "260"
]
let valueTwo = [
"title": "April 24th",
"value": "260"
]
var historyData = [valueOne, valueTwo]
但这给了我一个编译器错误
xxxController.type没有名为'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
。
相反,在这种情况下,应将它们设置为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]
}
// ....
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句