【发布时间】:2014-06-19 02:51:50
【问题描述】:
我想声明几个数组并将它们分配为字典中键的值。
代码如下:
class ViewController: UIViewController {
let colorsArray = ["Blue", "Red", "Green", "Yellow"]
let numbersArray = ["One", "Two", "Three", "Four"]
let myDictionary = ["Colors" : colorsArray, "Numbers" : numbersArray]
override func viewDidLoad() {
super.viewDidLoad()
// etc.
这会产生以下错误:
ViewController.Type does not have a member named 'colorsArray'
所以....
我尝试像这样修改我的字典声明:
let myDictionary:Dictionary<String, Array> = ["Colors" : colorsArray, "Numbers" : numbersArray]
这给了我一个更好的错误:
Reference to generic type 'Array' requires arguments in <...>
我尝试了各种其他修复方法 - 没有任何效果。
这在 Objective-C 中是小菜一碟,但在 Swift 中...?
解决方案:
将字典声明语句移动到viewDidLoad 修复它:
class ViewController: UIViewController {
let colorsArray = ["Blue", "Red", "Green", "Yellow"]
let numbersArray = ["One", "Two", "Three", "Four"]
override func viewDidLoad() {
super.viewDidLoad()
let myDictionary = ["Colors" : colorsArray, "Numbers" : numbersArray]
// etc.
我不太明白为什么会这样,但它现在确实有效。
【问题讨论】:
-
work for me。试试这个
let myDictionary:Dictionary<String, Array<String>> = ["Colors" : colorsArray, "Numbers" : numbersArray] -
我试过了!这是我尝试过的众多变体之一——因为它看起来正确——但我得到了同样的错误
ViewController.Type does not have a member named 'colorsArray'这怎么可能?您是在 Playgrounds 中还是在实际的 Xcode 项目中这样做的? -
我在 REPL 中尝试过。您需要显示整个代码。我认为您在
class Foo { /*code here*/ }中有代码。但我只试过func foo() { /*code here*/} -
你所说的让我走上正轨 - 查看已编辑的问题。
-
下面会有一些长答案,但简短的答案是,在所有属性都被赋值之前,你不能在初始化过程中使用 self 。因此,由于 myDictionary 仍未分配,因此您不能使用 self.colorsArray 对其进行初始化。
标签: arrays dictionary swift