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.

3
  • 1
    you mean a dictionary!? Commented Jan 2, 2017 at 18:57
  • I don't know luk, If that is the best solution then why not. But I don't know how to use it. Commented Jan 2, 2017 at 18:58
  • 3
    you should start reading a bit about swift developer.apple.com/library/content/documentation/Swift/… Commented Jan 2, 2017 at 18:59

2 Answers 2

11

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

Sign up to request clarification or add additional context in comments.

Comments

5

You need to use dictionary with dictionaries as values:

let countries = ["UK": ["gold_medal" : 59,
                        "prime_minister" : "XYS"],
                 "Germany": ["gold_medal" : 17,
                        "prime_minister" : "abc"]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.