Swift Dictionaries:不可能让一个数组成为一个键的价值吗?

sir*_*333 4 arrays dictionary swift

我想声明几个数组并将它们指定为字典中键的值.

这是代码:

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.
Run Code Online (Sandbox Code Playgroud)

这会产生以下错误:

ViewController.Type does not have a member named 'colorsArray'
Run Code Online (Sandbox Code Playgroud)



所以....

我尝试修改我的字典声明,如下所示:

let myDictionary:Dictionary<String, Array> = ["Colors" : colorsArray, "Numbers" : numbersArray]
Run Code Online (Sandbox Code Playgroud)

这给了我一个更好的错误:

Reference to generic type 'Array' requires arguments in <...>
Run Code Online (Sandbox Code Playgroud)


我尝试了各种其他修复 - 没有任何作用.

这在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.
Run Code Online (Sandbox Code Playgroud)

我不明白为什么会这样,但现在确实有效.

Wes*_*gne 5

在您的代码中,您没有初始化colorsArray,numbersArray并且myDictionary您正在指定一个默认值,如果init()没有设置默认值.您不允许在属性的默认值中引用其他属性,因为(我推测一点)它们的设置顺序无法保证.

简单的事情

class Test {
    let a = 3
    let b = 5
    let c = a * b
}
Run Code Online (Sandbox Code Playgroud)

以与初始代码相同的方式失败.要设置cmyDictionary根据需要,我们必须在初始化程序中执行此操作,而不是使用默认值:

class Test {

    let a = 3
    let b = 5        
    let c: Int

    init () {
        c = a*b
    }
}
Run Code Online (Sandbox Code Playgroud)

(请注意,不可变属性在内部是可变的init,这是我们使用它的方式let c.)

因此,与您的初始代码最接近的解决方案是:

class ViewController : UIViewController {
    let colorsArray = ["Blue", "Red", "Green", "Yellow"]
    let numbersArray = ["One", "Two", "Three", "Four"]

    let myDictionary: Dictionary<String, Array<String>>

    init() {
        myDictionary = ["Colors" : colorsArray, "Numbers" : numbersArray]
        super.init()
    }

    // etc
}
Run Code Online (Sandbox Code Playgroud)