Skip to content
Advertisement

How can I create Associative array in Swift 3

Hi I am very new to Swift and am trying to use array.

I want to create an array in swift3 similar to this PHP array as below:

$countries = array(
                   "UK"=>array(
                          "gold_medal" => 59,
                          "prime_minister" => 'XYZ'
                              ),
                    "Germany"=>array(
                          "gold_medal" => 17,
                          "prime_minister" => 'abc'
                              ),
                  )

In the array above the country name are dynamic variables.

Advertisement

Answer

These are called dictionaries in Swift, and you can create one like this:

let countries: [String: Any] = [
        "UK": ["gold_medal": 59, "prime_minister": "xyz"],
        "Germany": ["gold_medal": 17, "prime_minister": "abc"]
    ]

EDIT: Swift is great at inferring the variable type from the value that is being assigned, which is why we can write

let count = 5

and the compiler will figure out that count is of type Int. However, with the dictionary example above, Xcode (8.2.1) throws a warning heterogenous collection literal could only be inferred to ‘[String : Any]’; add explicit type annotation if this is intentional, which is why the example includes the type [String: Any].

More about dictionaries in The Swift Programming Language

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement