斯威夫特山地车
Swift Dictionary is one of the important collection types. Let’s get started by launching the playground in XCode.
Swift字典是重要的收藏类型之一。 让我们从XCode启动游乐场开始。
The following dictionary we initialize has the key of type String
and value of type Int
:
我们初始化的以下字典具有String
类型的键和Int
类型的值:
var countryCodes = [String: Int]()
countryCodes["India"] = 91
countryCodes["USA"] = 1
In the above code we initialise the dictionary in square brackets. The key is on the left of the colon and the value is on the right.
在上面的代码中,我们在方括号中初始化字典。 键在冒号的左边,值在右边。
The above is the shorthand syntax. The full syntax of a dictionary is:
以上是速记语法。 字典的完整语法为:
let dictionary:Dictionary = [:]
Alternatively, we can define a dictionary like:
另外,我们可以定义一个字典,例如:
var secondDictionary = ["Swift" : "iOS", "Java" : "Android" , "Kotlin" : "Android"]
secondDictionary["Java"] //"Android"
secondDictionary["Kotlin"] //"Android"
secondDictionary["Java"] //nil
Swift infers the type of the Dictionary as
. If a key doesn’t exist, it returns a nil
. To remove a key we just need to set the value to nil
.
Swift将Dictionary的类型推断为
。 如果键不存在,则返回nil
。 要删除键,我们只需要将值设置为nil
。
removeAll()
method is used to clear the contents of a dictionary. removeAll()
方法用于清除字典的内容。 count
property is used to get the number of key-value pairs. count
属性用于获取键值对的数量。 isEmpty
returns the boolean which tells whether the dictionary is empty or not. isEmpty
返回布尔值,该布尔值isEmpty
字典是否为空。 first
returns the first element(key/value pair of the dictionary). first
返回第一个元素(字典的键/值对)。 removeValue(forKey: )
removes the value at the specified key. The value can be stored in a variable/constant. removeValue(forKey: )
删除指定键处的值。 该值可以存储在变量/常量中。 keys
and values
property on dictionary to get the array of keys and values respectively. 我们可以在字典上调用keys
和values
属性来分别获取键和值的数组。 print(countryCodes) // ["India": 91, "USA": 1]
print(countryCodes.first) //prints Optional((key: "India", value: 91))
let returnedValue = countryCodes.removeValue(forKey: "USA") // 1
countryCodes.removeAll()
countryCodes.count //0
countryCodes.isEmpty //true
print(countryCodes) //prints : [:]
var keysArray = Array(secondDictionary.keys)
To iterate over a Dictionary in Swift, we use Tuple and a for-in loop.
为了迭代Swift中的Dictionary,我们使用Tuple和for-in循环。
for (key,value) in secondDictionary
{
print("key is \(key) and value is \(value)")
}
//Prints
//key is Java and value is Android
//key is Kotlin and value is Android
//key is Swift and value is iOS
Since dictionaries are not ordered, you can’t predict the order of iteration.
由于字典没有顺序,因此您无法预测迭代的顺序。
If the key doesn’t exist, instead of returning a nil, we can set a default value as shown below.
如果键不存在,则可以设置默认值,而不是返回nil,如下所示。
secondDictionary["Python", default: "No Value"] // "No Value"
We’ve converted Swift Dictionary to Swift Arrays to get keys and values array.
Now let’s merge two arrays to create a dictionary.
我们已经将Swift字典转换为Swift数组以获取键和值数组。
现在,让我们合并两个数组以创建字典。
let keys = ["August", "Feb", "March"]
let values = ["Leo", "Pisces", "Pisces"]
let zodiacDictionary = Dictionary(uniqueKeysWithValues: zip(keys,values))
print(zodiacDictionary)
zip
creates a sequence of pairs built out of two underlying sequences.
zip
创建一个由两个基础序列组成的成对序列。
What if we reverse the keys and values in the above code. It’ll have duplicate keys. Let’s look at how to handle duplicate keys using zip.
如果我们反转上面代码中的键和值,该怎么办? 它会有重复的密钥。 让我们看看如何使用zip处理重复密钥。
let zodiacs = ["Leo", "Pisces", "Pisces", "Aries"]
let repeatedKeysDict = Dictionary(zip(zodiacs, repeatElement(1, count: zodiacs.count)), uniquingKeysWith: +)
print(repeatedKeysDict) //["Leo": 1, "Pisces": 2, "Aries": 1]
The dictionary is of the type [String:Int]
The value for each key is incremented if there are repeatable elements with the default value set to 1.
字典的类型为[String:Int]
如果存在默认值设置为1的可重复元素,则每个键的值将递增。
The above code indirectly gets the number of occurrences of each word.
上面的代码间接获取每个单词的出现次数。
Swift 4 has given rise to filtering and mapping functions on a Dictionary as shown below.
Swift 4产生了对Dictionary的过滤和映射功能,如下所示。
let filtered = repeatedKeysDict.filter { $0.value == 1 }
print(filtered) //prints ["Leo": 1, "Aries": 1]
let mapped = filtered.mapValues{"Occurence is \($0)"}
print(mapped) //prints ["Leo": "Occurence is 1", "Aries": "Occurence is 1"]
$0.values
gets the current value in filter
.
$0 gets the current value in mapValues
$0.values
获取filter
的当前值。
$ 0获取mapValues
的当前值
This brings an end to this tutorial.
本教程到此结束。
References : Apple Docs
参考文献: Apple Docs
翻译自: https://www.journaldev.com/19524/swift-dictionary
斯威夫特山地车