斯威夫特山地车_斯威夫特字典

斯威夫特山地车

Swift Dictionary is one of the important collection types. Let’s get started by launching the playground in XCode.

Swift字典是重要的收藏类型之一。 让我们从XCode启动游乐场开始。

斯威夫特字典 (Swift Dictionary)

  • Swift Dictionary is a collection of key-value pair elements. They are an unordered list of values of the same type with unique keys. Under the hood, they are just HashTable.

    Swift字典是键值对元素的集合。 它们是具有唯一键的相同类型的值的无序列表。 在后台,它们只是HashTable。
  • Hashtable is data structure composed of Arrays and a hash function, to say the least.

    至少可以说,哈希表是由数组和哈希函数组成的数据结构。
  • They are very useful when you need to search for something from a large data. In such cases Arrays, LinkedList would consume more time typically with the complexity of O(N) or O(logN). This is where Hashtable are useful as they can return you the search result within O(1) time normally.

    当您需要从大数据中搜索内容时,它们非常有用。 在这种情况下,LinkedList通常会花费更多时间,而复杂度为O(N)或O(logN)。 这是Hashtable有用的地方,因为它们可以正常在O(1)时间内返回搜索结果。
  • How are the books in your library arranged so that you can find your favorite book easily? How do you search a word in your dictionary? The answer is Hashtables. They use a hash function to convert the data into a simpler one such that you can easily trace the value from the key.

    图书馆中的书籍如何排列,以便您可以轻松找到自己喜欢的书籍? 您如何在字典中搜索单词? 答案是哈希表。 他们使用哈希函数将数据转换为更简单的数据,以便您可以轻松地从键中跟踪值。
  • Swift Dictionaries are value types. Not reference types.

    Swift字典是值类型。 不是参考类型。

创建字典 (Creating a dictionary)

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<KeyType, ValueType> = [:]

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 <String, String>. 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的类型推断为<String, String> 。 如果键不存在,则返回nil 。 要删除键,我们只需要将值设置为nil

Swift字典的属性和功能 (Swift Dictionary Properties and Functions)

  • 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: )删除指定键处的值。 该值可以存储在变量/常量中。
  • We can call keys and values property on dictionary to get the array of keys and values respectively.

    我们可以在字典上调用keysvalues属性来分别获取键和值的数组。
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)

遍历Swift字典 (Iterating over a Swift Dictionary)

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.

由于字典没有顺序,因此您无法预测迭代的顺序。

不存在密钥的默认值 (Default Value for non-existing key)

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"

从两个数组创建字典 (Creating a Dictionary from two arrays)

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创建一个由两个基础序列组成的成对序列。

处理重复的密钥 (Handling Duplicate Keys)

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.

上面的代码间接获取每个单词的出现次数。

字典过滤和映射 (Dictionary Filtering and Mapping)

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

斯威夫特山地车

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值