Swift Language Tutorial for Beginner 7 - Dictionary

In Swift Language Tutorial for Beginner 6 - Array, we’ve seen the use of list types in Swift, and now let’s look at dictionary types in Swift - Dictionary。

In Swift, dictionary types are used to store key and value pairs. Similar to Map in Java

Declaration and initialization

The syntax of the declaration dictionary is: var dictionary_name [param1:param2]

Represents a dictionary type in which param1 is the key type param2 is a value type, such as:

1
var dic1:[Int:String]

Generic are also available to use:

1
var dic2:Dictionary<Int,String>

This way has the same effect as [:]

When you create a dictionary, you can also not display the type of the declaration dictionary, and you can make the compiler automatically infer by assigning an initial value

1
var dic3 = ["1":"one"]

It is also possible to declare and then assign values, such as dic1 and dic2 declared above

1
2
dic1 = [1:"1",2:"2",3:"3"]
dic2 = Dictionary(dictionaryLiteral: (1,"1"),(2,"2"),(3,"3"))

You can also create an empty dictionary

1
2
var dic4:[Int:Int] = [:]
var dic5:Dictionary<Int,Int> = Dictionary()

Determine the number of elements

Use the count property

1
dic1.count

Determine if the dictionary is empty

Use the isEmpty property

1
2
3
if dic4.isEmpty{
print("Dictionary is empty.")
}

Basic access operations

  1. Get the value by key
    1
    print(dic1[1])

In order to avoid the absence of a key in the dictionary and result in the value being empty, we can also use the if let method we have in the optional type, as follows:

1
2
3
if let value = dic2[1] {
print("The Value is \(value)")
}
  1. Modify value
1
dic1[1]="0"
  1. Append a item
1
dic1[4] = "4"

Dictionaries are out of order, and key is not necessarily an integer

Use updateValue to update the value

1
dic1.updateValue("1", forKey: 1)

The method looks the same as the result of a direct assignment, but the method actually has a return value, so that you can get the original value at the same time as the update, such as:

1
2
3
if let oldValue = dic1.updateValue("One", forKey: 1) {
print("Old Value is \(oldValue)")
}

Delete Item

  1. Delete item by key
1
dic1.removeValue(forKey: 1)
  1. Delete all items
1
dic1.removeAll()

Iterate item

  1. Iterate item by key
1
2
3
for item in dic2.keys {
print(item)
}
  1. Iterate item by value
1
2
3
for item in dic2.values {
print(item)
}
  1. Iterate directly through the dictionary
1
2
3
for item in dic2 {
print(item)
}

Or

1
2
3
for (key,value) in dic2 {
print("\(key):\(value)")
}

Next

Next, we’ll take a brief look at Set types in Swift. Swift Language Tutorial for Beginner 8 - Set

本文标题:Swift Language Tutorial for Beginner 7 - Dictionary

文章作者:Morning Star

发布时间:2022年01月15日 - 14:01

最后更新:2022年01月18日 - 15:01

原始链接:https://www.mls-tech.info/app/swift/swift-tutorial-7-dictionary-en/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。