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:
JavaScript
x
$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:
JavaScript
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
JavaScript
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