【问题标题】:initialise array of dictionaries in swift giving error在快速给出错误时初始化字典数组
【发布时间】:2015-09-03 13:58:55
【问题描述】:

我很快就面临着奇怪的行为。我有

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 中尝试这两种代码时,它们运行良好。

我的问题是我在第一个 sn-p 中做错了什么?

【问题讨论】:

  • 您需要在类的方法中声明您的代码。你的语法很好!

标签: ios iphone swift xcode6


【解决方案1】:

假设你这样做:

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

    // ....
}

【讨论】:

    【解决方案2】:

    您的代码没问题,但确保您在某个方法中编写 sn-p。例如viewDidLoad()

    【讨论】:

      猜你喜欢
      • 2016-05-27
      • 1970-01-01
      • 2011-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-01
      • 1970-01-01
      相关资源
      最近更新 更多