Swift's initial "Swift" dictionary

Source: Internet
Author: User


As the name implies, when we look up a dictionary, we look at the resources we need to find based on the index, and in Swift, every object in the dictionary contains a key and a value, and we use key to find the value corresponding to the current key. Unlike arrays, data items in a dictionary do not have a specific storage order in the dictionary.

Similar to the array in swift, the SWIFT variable dictionary and the immutable Dictionary are distinguished only by the definition of Let and Var, and in OC by Nsdictionary and Nsmutabledictionary.

Swift's dictionary is defined as: (Key:value), there is a limit to key and value, the only limit of key is hash, so as to ensure that key is unique, the address of key is: addr = hash (key), value = HASHTAVLE[ADDR], first obtain the address of the key, and then in the hash table by the address of the found key to find the value.


Structure of the dictionary:
Similar to arrays, dictionaries have a lot of similar syntax:
var dict = ["Key1": "Value1", "Key2": "value2"]println (dict)

Output: [Key1:value1, Key2:value2]
We know that Swift has the function of type derivation, we don't have to define the type of key and value, and the OS can help us deduce that both key and value are string types.

We can also define the type of key and value 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 of defining the omission:
var dict3: [String:int] = ["Key3": 3, "Key4": 4]println (DICT3)

Output: [Key4:4, Key3:3]

We can also use construct statements like arrays to create an empty dictionary:
var emptydict = dictionary<string, string> ()

At this point we create an empty dictionary of keys and value that are strings;
If we do not know what type of data to put on when we create the dictionary, we can also use Swift's type derivation function to automatically derive the data item at a later time:
var emptyDict2 = [:]


operation of the array:
The underlying operation of the data includes additions and deletions, as well as the operation of the dictionary:
When adding an item to a dictionary, we can add new items by subscript, such as add an item to Dict:
dict["Key3"] = "Value3" println (dict)

At this time there are three items in Dict, the output is: [Key1:value1, Key3:value3, Key2:value2]

You can also use the subscript to manipulate the value of an item in the dictionary:
dict["Key1"] = "Novalue" println (dict)

The output at this time is: [Key1:novalue, Key3:value3, Key2:value2]
Swift also provides a Updatevalue method to update the values in the dictionary,
Dict.updatevalue ("123", Forkey: "Key4") println (Dict)

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

As with arrays, we can get the number of data items in the dictionary by reading the dictionary's read-only familiarity with count.

If we need to remove a data item from a dictionary, there are 2 different ways:
1. Use subscript to assign a value of nil to the corresponding value of a key, and this data item is removed from the dictionary:
dict["Key4"] = nilprintln (dict)

From the output we can clearly see that the corresponding data item Key4 has been removed from the dictionary;
2. Functions provided by Swift: Removevalueforkey:
Dict.removevalueforkey ("Key1") println (Dict)

3. Use RemoveAll to remove all data items.


Dictionary Traversal
Remember that there are 2 ways in the array traversal, one is for-in loop to traverse, one is enumerate to traverse the data item and the index returns a meta-ancestor, there are several ways in the traversal of the dictionary:
1, for-in cycle:
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 are \ (value)")}for (Key, _) in Dict {    println (key)}for (_, value) in Dict {    println (value)}


The output is:

(Key1, value1) (Key3, Value3) (Key2, value2) key is Key1 and value is Value1key are Key3 and value is Value3key are Key2 and value is Value2key1key3key2val Ue1value3value2


We see these kinds of ways, the first direct print out the value of the key value pairs, the second one of our conditions to write a meta-ancestor, printing key and value, the third we added an underscore, we do not care about the value of the second item, we only need the first item, The fourth approach is that we only care about value:


2, we can get acquainted with the keys of the dictionary to return all the key of the current dictionary, also can return all the value of the dictionary,
For keys in Dict.keys {    println (keys)}for values in Dict.values {    println (values)}

The keys and values of the dictionary return a collection, and we can construct a new array directly using the keys or the Values property:
Let Keysarray = Array (Dict.keys) println (Keysarray)

The data items in the dictionary are unordered, and when we traverse the dictionary, key and value are rearranged and the order is not fixed.



You are welcome to guide and learn together.





Swift's initial "Swift" dictionary

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.