在 swift 中初始化字典数组给出错误

initialise array of dictionaries in swift giving error

我在 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 中尝试这两种代码时,它们都工作正常。

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

您的代码没问题,但请确保您是在某种方法中编写代码段。例如 viewDidLoad().

假设你这样做:

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]
    }

    // ....
}