Swift Dictionaries: is it impossible to have an array for a value for a key?

I want to declare a pair of arrays and assign them as values ​​for keys in a dictionary.

Here is the code:

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.

This results in the following error:

ViewController.Type does not have a member named 'colorsArray'



So....

I tried changing my ad in the dictionary as follows:

let myDictionary:Dictionary<String, Array> = ["Colors" : colorsArray, "Numbers" : numbersArray]

And that gives me an even better mistake:

Reference to generic type 'Array' requires arguments in <...>


I tried all kinds of other fixes - nothing works.

This / was part of the cake in Objective-C, but in Swift ...?

SOLUTION :
Moving the dictionary declaration operator in viewDidLoadfixed:

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.

I do not quite understand why this is so, but now it works.

+4
source share
1 answer

colorsArray, numbersArray myDictionary , , , init() . , ( ) , , .

- ,

class Test {
    let a = 3
    let b = 5
    let c = a * b
}

, . c myDictionary , :

class Test {

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

    init () {
        c = a*b
    }
}

( , 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
}
+5
source

Source: https://habr.com/ru/post/1545156/


All Articles