Collection classes in swift language-usage of dictionaries

Source: Internet
Author: User

Dictionary

A dictionary is a storage that stores multiple types of data. Each value is associated with a unique key as the identifier of the value data in the dictionary. Unlike the data items in the array, the data items in the dictionary are not in specific order. We use dictionaries when we need to access data through Identifiers (KEYS). This method is largely the same as we use dictionaries to search for meaning in the real world.

 

When using the swift dictionary, you must specify the key and value types that can be stored. Unlike the objective-C nsdictionary and nsmutabledictionary classes, any type of objects can be used as keys and values without providing any essential information about these objects. In swift, keys and values that can be stored in a specific dictionary must be clearly defined in advance by explicit type annotation or type inference.

 

The swift dictionary is defined by dictionary <keytype, valuetype>. The keytype is the data type of the Middle-key in the dictionary, and the valuetype is the data type corresponding to the stored values of these keys in the dictionary.

 

The unique restriction of keytype is that it can be hashed to ensure that it is unique. All basic swift types (such as string, Int, double, and bool) are hashable by default, all these types can be used as keys in the dictionary. Enumeration members with unassociated values (see enumeration) can also be hashed by default.

 

 

Dictionary literal statement

We can use dictionary literal statements to construct a dictionary. They have similar syntax as the array literal statements we just introduced. A dictionary literal statement is a simple statement that defines a dictionary set with one or more key-value pairs.

 

A key-value pair is a combination of a key and a value. In a dictionary literal statement, the keys and values of each key-value pair are separated by colons. These key-value pairs form a list. These key-value pairs are included in square brackets and separated by commas:

[Key 1: value 1, key 2: Value 2, key 3: Value 3]

The following example creates a dictionary for storing the name of an international airport. In this dictionary, the key is a three-letter code related to international air transportation. The value is the airport Name:

 

var airports: Dictionary<String,String> = ["TYO": "Tokyo", "DUB":"Dublin"]

The airports dictionary is defined as a dictionary <string, string>, which means that the keys and values of this dictionary are of the string type.

 

Note:

 

The airports dictionary is declared as a variable (using the VaR keyword) instead of a constant (let keyword) because more airport information will be added to this dictionary.

The airports dictionary is initialized using a dictionary literal statement, which contains two key-value pairs. The first key is tyo and the value is Tokyo. The key of the second pair is Dub and the value is Dublin.

 

This dictionary statement contains two string: string type key-value pairs. They correspond to the types declared by the airports variable (a dictionary with only the string key and string value). Therefore, this dictionary literal statement is an airport dictionary that constructs two initial data items.

 

Like arrays, if we use a literal statement to construct a dictionary, we do not need to define the type clearly. Airports can also be briefly defined using this method:

var airports = ["TYO":"Tokyo", "DUB": "Dublin"]

Because all the keys and values in this statement are of the same data type, Swift can infer that the dictionary <string, string> is the correct type of the airports dictionary.

 

Read and modify dictionaries

You can use the dictionary methods and attributes to read and modify the dictionary, or use the subscript syntax. Like arrays, we can use the read-only attribute count of the dictionary to obtain the number of data items in a dictionary:

 

Println ("The Dictionary of airportscontains \ (airports. Count) items.") // print "thedictionary of Airports contains 2 items." (This dictionary has two data items)


We can also use subscript syntax in the dictionary to add new data items. You can use a key of the appropriate type as the subscript index and assign a new value of the appropriate type:

 

Airports ["lhr"] = "London" // The airports dictionary now has three data items


We can also use the subscript syntax to change the value corresponding to a specific key:

 

Airports ["lhr"] = "londonheathrow" // The value corresponding to "lhr" is changed to "londonheathrow


As another subscript method, the updatevalue (forkey :) method of the dictionary can be used to set or update values corresponding to a specific key. As shown in the preceding example, the updatevalue (forkey :) method sets or updates an existing value when the key does not have a corresponding value. Unlike the subscript method above, this method returns the original value before the updated value. In this way, we can check whether the update is successful.

 

The updatevalue (forkey :) function returns an optional value that contains a dictionary value type. For example: for the dictionary that stores string values, this function returns a string? Or an optional string value. If the value exists, the value is equal to the value to be replaced. Otherwise, the value is nil.

 

If let oldvalue = airports. updatevalue ("Dublin internation", forkey: "Dub") {println ("the old value for dub was \ (oldvalue ). ")} // output" The oldvalue for dub was Dublin. "(the original dub value is Dublin)


We can also use the subscript syntax to retrieve the values corresponding to a specific key in the dictionary. Because a key without a value is possible, the optional type returns the related value of the key; otherwise, the NIL is returned:

 

If let airportname = airports ["Dub"] {println ("the name of the airport is \ (airportname ). ")} else {println (" that airport is not in the airports dictionary. ")} // print" the name ofthe airport is Dublin internation. "(the airport name is Dublin International)


We can also use the subscript syntax to remove a key-value pair from the dictionary by assigning the corresponding value of a key to nil:

 

Airports ["APL"] = "appleinternation" // "Apple internation" is not a true APL airport. Delete airports ["APL"] = nil // APL and it is now removed


In addition, the removevalueforkey method can also be used to remove key-value pairs from the dictionary. If a key-Value Pair exists, this method will remove the key-Value Pair and return the removed value or return nil if no value exists:

 

if let removedValue =airports.removeValueForKey("DUB") {   println("The removed airport's name is \(removedValue).")} else {   println("The airports dictionary does not contain a value forDUB.")}// prints "The removed airport's nameis Dublin International." 


Dictionary Traversal

We can use a for-in loop to Traverse Key-value pairs in a dictionary. Each data item in the dictionary is returned in the form of (Key, value) tuples, and we can use temporary constants or variables to break down these tuples:

 

for (airportCode, airportName) in airports{   prINTln("\(airportCode): \(airportName)")}// TYO: Tokyo// LHR: London Heathrow


For the for-in loop, see for loop.

 

You can also retrieve the keys or values of a dictionary by accessing its keys or values attributes (all of which can be traversed:

 

for airportCode in airports.keys {   prINTln("Airport code: \(airportCode)")}// Airport code: TYO// Airport code: LHR for airportName in airports.values {   prINTln("Airport name: \(airportName)")}// Airport name: Tokyo// Airport name: London Heathrow


If we only need to use a dictionary's key set or value set as a parameter to accept the API of an array instance, we can directly use the keys or values attribute to construct a new array:

 

let airportCodes = Array(airports.keys)// airportCodes is ["TYO","LHR"] let airportNames = Array(airports.values)// airportNames is ["Tokyo","London Heathrow"]

Note:

The swift dictionary type is an unordered set type. The dictionary keys, values, and key-value pairs are re-arranged during traversal, and the order is not fixed.

Create an empty dictionary

We can create an empty dictionary using the constructor syntax like an array:

VaR namesofintegers = dictionary <int, string> () // namesofintegers is an empty dictionary <int, string>

In this example, an int and string empty dictionary is created to store the English name of the integer. Its key is 'int' type and its value is 'string' type.

If the context already provides the information type, you can use an empty dictionary literal statement to create an empty dictionary and record it as [:] (put a colon in brackets ):

Namesofintegers [16] = "Sixteen" // namesofintegers now contains a key-Value Pair namesofintegers = [:] // namesofintegers into an int, an empty string dictionary


Note:

 

In the background, swift arrays and dictionaries are implemented by generics. For more information about generics and collections, see generics.

 

Set Variability

Arrays and dictionaries store variable values in a single set. If we create an array or dictionary and allocate it to a variable, the set will be variable. This means that we can add more or remove existing data items after creation to change the size of this set. In contrast, if we assign an array or dictionary to a constant, it is immutable and its size cannot be changed.

 

For the dictionary, non-variability also means that we cannot replace the values corresponding to any of the existing keys. The content of an unchangeable dictionary cannot be changed after it is set for the first time. Immutable rows are a little different for arrays. Of course we cannot try to change the size of any immutable array, but we can reset the value corresponding to the existing index. This makes the swift array great when the size is fixed.

 

The mutable behavior of the SWIFT array affects how the array instance is allocated and modified. For more information, see the behavior of the Set in assignment and replication.

 

Note:

 

It is a good habit to create an unchangeable array without changing the array size. The swift compiler can optimize the set we created.

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.