[Swift first sight] Swift dictionary and swift dictionary

Source: Internet
Author: User

[Swift first sight] Swift dictionary and swift dictionary

As the name suggests, when we look up the dictionary, we will search for the resources we need to find Based on the index. This is also true in swift. Every object in the dictionary contains a key and a value, we use the key to find the value corresponding to the current key. Different from the array, the data items in the dictionary do not have a specific storage order in the dictionary.

Similar to arrays in Swift, the Swift variable dictionary and the non-variable dictionary are differentiated only by the let and var definitions, while the NSDictionary and NSMutableDictionary are distinguished in OC.

The Swift dictionary is defined as: (key: value). key and value are restricted. The unique key restriction can be hash, so that the key is unique, the address of the key is addr = hash (key), value = hashTavle [addr], and the key address is obtained first, in the hash table, find the value through the key address.


Dictionary structure:
Similar to arrays, dictionaries also have many similar syntaxes:

var dict = ["key1":"value1" , "key2":"value2"]println(dict)

Output: [key1: value1, key2: value2]
We know that swift has the type derivation function. We do not need to define the types of key and value. The OS can help us to export keys and values of the String type.

We can also define the key and value types in the dictionary when declaring a dictionary.
var dict2 : Dictionary<String, Int> = ["key1":1, "key2":2]println(dict2)

Output: [key1: 1, key2: 2]

Of course, we also have a way to omit the definition:
var dict3 : [String : Int] = ["key3": 3, "key4":4]println(dict3)

Output: [key4: 4, key3: 3]

We can also create an empty dictionary using a constructor statement like an array:
var emptyDict = Dictionary<String, String>()

Now we create an empty dictionary where both the key and value are strings;
If we do not know what type of data to store when creating a dictionary, we can also use the swift type derivation function to automatically derive data when adding data items in the future:
var emptyDict2 = [ : ]


Array Operations:
Basic data operations include addition, deletion, modification, and query. The same is true for dictionary operations:
When adding a new dictionary item, we can add a new data item by subscript, for example, adding a new item to dict:
dict["key3"] = "value3"println(dict)

In this case, three items in dict are output: [key1: value1, key3: value3, key2: value2]

When you modify a value in a dictionary, you can use a subscript to perform the operation:
dict["key1"] = "NOValue"println(dict)

The output is: [key1: NOValue, key3: value3, key2: value2]
Swift also provides an updateValue method to update the value in the dictionary,
dict.updateValue("123", forKey: "key4")println(dict)

If the key exists, the value corresponding to the key is updated. If the key does not exist, a new record is added.

Like arrays, we can get the number of data items in the dictionary through the dictionary read-only and familiar count.

If we need to remove a data item from a dictionary, there are two ways:
1. assign a value of nil to the corresponding value of a key in the way of the lower mark. This data item is removed from the dictionary:
dict["key4"] = nilprintln(dict)

From the output, we can see that the data items corresponding to key4 have been removed from the dictionary;
2. Use the function removeValueForKey provided by swift:
dict.removeValueForKey("key1")println(dict)

3. Use removeAll to remove all data items.


Dictionary Traversal
I still remember that there are two methods in array traversal: one is for-in loop traversal, the other is enumerate to traverse data items and the index returns a ancestor, the following methods are available in dictionary traversal:
1. for-in loop:
var dict = ["key1" : "value1" , "key2" : "value2" , "key3" : "value3"]for key in dict{    println(key)}for (key,value) in dict{    println("key is \(key) and value is \(value)")}for (key, _) in dict {    println(key)}for (_, value) in dict {    println(value)}


Output:

(key1, value1)(key3, value3)(key2, value2)key is key1 and value is value1key is key3 and value is value3key is key2 and value is value2key1key3key2value1value3value2


We can see that the first method directly prints the value of the key-value pair, and the second method writes a tuple in our condition to print the key and value respectively, in the third case, we add an underscore to indicate that we do not care about the value of the second item. We only need the first item, and the fourth method means that we only care about the value:


2. We can use the dictionary keys to get familiar with the current dictionary to return all keys, and we can also return all values of the dictionary,
for keys in dict.keys {    println(keys)}for values in dict.values {    println(values)}

The dictionary keys and values return a set. We can directly use the keys or values attribute to construct a new array:
let keysArray = Array(dict.keys)println(keysArray)

The data items in the dictionary are unordered. When we traverse the dictionary, keys and values are rearranged, and the order is not fixed.



Thank you for your guidance and learning together.





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.