Welcome to Swift (initial translation and annotations of Apple's official Swift document 23)---154~162 page (chapter III-collection type)

Source: Internet
Author: User

Dictionaries (dictionary)

A dictionary is like a container that can hold a number of values of the same type. Each value has a unique key associated with it, and the key in the dictionary acts as if it were an identity card for each value. Unlike elements in an array, each element in the dictionary does not have a fixed sequence. When you use a dictionary and you want to query a value, You need to use the value's identity (key). It's like you use a dictionary in your life to find the definition of a word.

In Swift, the type that a dictionary can store needs to be clearly defined. This is very different from the Nsdictionary class and the Nsmutabledictionary class in OC, where they can use arbitrary objects as keys and values without having to provide any information about those classes. In Swift , the type of key and value in the dictionary must always be explicit.

In Swift, the dictionary type is written as: Dictionary<keytype, Valuetype>, where KeyType is the type of key in the dictionary, and ValueType is the type of value that can be stored in the dictionary.

The only qualification here is that the KeyType must be hashed (hashable), which means that it must provide an identity that can make itself unique. All of the basic types in swift (such as String, Int, Double, and Bool) are all available by default Greek. And these basic types can be used as keys in the dictionary. Enumeration members that do not have an assigned value can be hashed by default.

Dictionary Literals (dictionary grammar /** Oh, the front may be translated wrong, please feel carefully * *)

Use the syntax of a dictionary to initialize a dictionary, which is the syntax and proximity of the array. This syntax can also be abbreviated as one or more key-value pairs.

A key-value pair contains one key (key) and one value (value). In the dictionary, the keys and values of the key-value pairs are separated by a colon. The key-value pair is separated from the key-value pair using a comma, and finally wrapped in brackets []:

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

The following code example creates a dictionary that stores the name of an international airport. In this dictionary, key is the three-letter IATA code, and value is the name of the airport:

var airports:dictionary<string, string> = ["Tyo": "Tokyo", "DUB": "Dublin"]

The dictionary airports is defined as the dictionary<string, string> type, which means that its key is a string type and its value is also a string type.

  Note the point:

The dictionary airports is a variable, not a constant. Because the following code example adds more airports to it.

The dictionary airports is initialized by a dictionary syntax that contains two key-value pairs. The first key-value pair is the key tyo and the value of Tokyo, and the second key-value pair is the key dub and the value Dublin

The dictionary syntax uses two string:string key-value pairs, which just match the declaration of the airports variable, so it is possible to initialize the dictionary airports with such a statement.

Like an array, you can omit the type of the dictionary if you use the deterministic type of the key value when initializing. Therefore, the initialization of airports can be abbreviated as:

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

This is because the type of the key and the type of the value match the assignment, so that the swift compiler can determine that the type of dictionary airports is dictionary<string, String>.

Accessing and modifying a Dictionary (Access and modify dictionaries)

You can access and modify a dictionary using the dictionary's methods and properties, or you can use subscript. As with arrays, you can use the read-only Count property of the dictionary to determine the number of entries in the dictionary:

println ("The Dictionary of Airports contains \ (airports.count) items.")

Prints "The Dictionary of Airports contains 2 items.

You can use the subscript to add a new entry to the dictionary, where the new key is the subscript type, and the value is assigned a new value that matches the type:

airports["LHR"] = "London"

The Airports Dictionary now contains 3 items

You can also use the subscript (key) to modify the corresponding value:

airports["LHR"] = "London Heathrow"

The value for "LHR" have been changed to "London Heathrow"

In addition to the above using subscript modified values, use the dictionary's Updatevalue (Forkey:) method to set or update the value of the corresponding key. Like using subscript, Method Updatevalue (forkey:) If you find that there is no key, you will create a new key and set the value. If there is a key, update the value of the key. Unlike using subscript, method Updatevalue (Forkey:) returns the old value after an update is performed, which allows you to check for updates.

The Updatevalue (forkey:) method returns an optional value of a value type. For example, the dictionary stores a value of type string, and this method returns a string. This optional value contains an old value (if the value of the key exists) or a nil ( If the value corresponding to key does not exist):

If Let OldValue = Airports.updatevalue ("Dublin International", Forkey: "DUB") {

println ("The old value for DUB is \ (oldValue).")

}

Prints "The old value for DUB is Dublin."

You can also use subscripts (key is used as subscript) to get the values in the dictionary. Because a key may not have a value, the return value is an optional type of value in the dictionary. Returns this value if the value corresponding to key is found in the dictionary, otherwise returns nil:

If let Airportname = airports["DUB"] {

println ("The name of the airport is \ (airportname).")

} else {

println ("that airport was not in the airports Dictionary.")

}

Prints "The name of the airport is Dublin International."

You can also use the subscript syntax to remove a pair of key values by assigning a value of nil to the value associated with the key:

airports["APL"] = "Apple International"

"Apple International" is a real airport for APL, so delete it

airports["APL"] = Nil

APL has now been removed from the dictionary

In addition, the Removevalueforkey method of the dictionary can also be used to remove key-value pairs. If a key-value pair exists, this method removes the key-value pair and returns the removed value, and if the key-value pair does not exist, this method puts it back to nil:

If Let Removedvalue = Airports.removevalueforkey ("DUB") {

println ("The removed airport ' s name is \ (removedvalue).")

} else {

println ("The Airports Dictionary does not contain a value for DUB.")

}

Prints "The removed airport ' s name is Dublin International."

Iterating over a Dictionary (traversal dictionary)

You can use the for-in loop to iterate through the key-value pairs in the dictionary, and each entry returned in the dictionary is a tuple of (key, value) that you can save in a temporary constant or variable:

For (Airportcode, Airportname) in airports {

println ("\ (Airportcode): \ (airportname)")

}

Tyo:tokyo

Lhr:london Heathrow

You can also iterate by accessing the Keys property and the values property of the dictionary:

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 you need to use the dictionary's key or value as an API for an array instance, you can use the keys and the values property to initialize a new array:

Let Airportcodes = Array (Airports.keys)

Airportcodes is ["Tyo", "LHR"]

Let Airportnames = Array (airports.values)

Airportnames is ["Tokyo", "London Heathrow"]

  Note the point:

In Swift, a dictionary type is an unordered collection. The order of keys and values and key-value pairs in the dictionary is not deterministic when traversing a dictionary.

Creating an empty Dictionary (create null dictionary)

Like arrays, you can create an empty dictionary of some kind by initializing the syntax:

var namesofintegers = Dictionary<int, string> ()

Namesofintegers is an empty dictionary<int, string>

In this code example, create an empty dictionary with the type int, String. Its key is the int type, and its values are the striing type.

If the type information for the dictionary has been confirmed, you can use an empty dictionary syntax (writing [:]) to create an empty dictionary:

NAMESOFINTEGERS[16] = "Sixteen"

Namesofintegers now contains 1 key-value pair

Namesofintegers = [:]

Namesofintegers is once again an empty dictionary of type Int, String

  Note the point:

In the swift background mechanism, the dictionary and array types are treated as a common set (generic collections)

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.