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:

JavaScript

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

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

JavaScript

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