简体   繁体   English

如何在 Swift 3 中创建关联数组

[英]How can I create Associative array in Swift 3

Hi I am very new to Swift and am trying to use array.嗨,我对 Swift 很陌生,正在尝试使用数组。

I want to create an array in swift3 similar to this PHP array as below:我想在 swift3 中创建一个类似于这个 PHP 数组的数组,如下所示:

$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.在上面的数组中,国家名称是动态变量。

These are called dictionaries in Swift, and you can create one like this:这些在 Swift 中被称为字典,你可以像这样创建一个:

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编辑:Swift 擅长从被赋值的值推断变量类型,这就是为什么我们可以写

let count = 5

and the compiler will figure out that count is of type Int .并且编译器会发现countInt类型。 However, with the dictionary example above, Xcode (8.2.1) throws a warning heterogenous collection literal could only be inferred to '[String : Any]';但是,在上面的字典示例中,Xcode (8.2.1) 抛出警告异构集合文字只能推断为 '[String : Any]'; add explicit type annotation if this is intentional , which is why the example includes the type [String: Any] .如果这是有意的则添加显式类型注释,这就是示例包含类型[String: Any]

More about dictionaries in The Swift Programming Language更多关于The Swift Programming Language 中的字典

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"]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM