Swift Tutorial 13-Dictionary dictionary and Nsdictionary

Source: Internet
Author: User
Tags hashable

Unlike OC dictionaries, Swift's dictionary can store not only the value of the object type, but also the base data type value, struct, and enumeration value;

The use of swift dictionaries is also more concise and more powerful.

Dictionaries are also structs in nature, and viewing documents can be seen:


A hash-based mapping from ' Key ' to ' Value ' instances. Also a///Collection of key-value pairs with no defined ordering.struct dictionary<key:hashable, value>: collecti Ontype, dictionaryliteralconvertible {typealias Element = (Key, Value) typealias Index = Dictionaryindex<key, Va  lue>//Create A dictionary with at least the given number of///elements worth of storage.    The actual capacity would be the///smallest power of 2 that ' s >= ' minimumcapacity '.  Init ()///Create a dictionary with at least the given number of///elements worth of storage.    The actual capacity would be the///smallest power of 2 that ' s >= ' minimumcapacity '.    Init (Minimumcapacity:int)///The position of the first element in a Non-empty dictionary.  Identical to ' EndIndex ' on an empty Dictionary/////Complexity:amortized O (1) If ' self ' does not wrap    A bridged///' Nsdictionary ', O (N) otherwise. var startindex:dictionaryindEx<key, value> {get}///The collection ' "Past the end" position. ' EndIndex ' is not a valid argument to ' subscript ', and are always//reachable from ' StartIndex ' by zero or    More applications of///' successor () '.    Complexity:amortized O (1) If ' self ' does not wrap a bridged//' nsdictionary ', O (N) otherwise. var endindex:dictionaryindex<key, value> {get}//Returns the ' Index ' for the given key, or ' nil ' if the key    is not///present in the dictionary.    Func Indexforkey (Key:key), Dictionaryindex<key, Value>?    Subscript (Position:dictionaryindex<key, value>), (Key, Value) {get} subscript (Key:key), Value? Update the value stored in the dictionary for the given key, or, if they//key does not exist, add a new Key-va    Lue pair to the dictionary.    Returns the value is replaced, or ' nil ' if a new key-value pair//was added. Mutating func UpdatevaluE (Value:value, Forkey key:key), value?    Remove the Key-value pair at index ' I '////invalidates all indices with respect to ' self '.    Complexity:o (\ ' count ' \). mutating func Removeatindex (Index:dictionaryindex<key, value>)///Remove a given Key and the associated Value F    Rom the dictionary.    Returns the value that is removed, or ' nil ' if the key is not present///in the dictionary.    mutating func Removevalueforkey (key:key), Value?    Remove all elements.    Postcondition: ' capacity = = 0 ' iff ' keepcapacity ' is ' false '.    Invalidates all indices with respect to ' self '.    Complexity:o (\ ' count ' \).    mutating func removeall (Keepcapacity:bool = default)//The number of entries in the dictionary.    Complexity:o (1) var count:int {get}///Return a *generator* over the (key, value) pairs. Complexity:o (1) func generate (), DictionarygenErator<key, value>//Create An instance initialized with ' elements '.    Init (dictionaryliteral elements: (Key, Value) ...) True iff ' count = 0 ' var isempty:bool {get}//A collection containing just the keys of ' self '///  /Keys appear in the same order as they occur as the '. 0 ' member///For Key-value pairs in ' self '.    Each key with the result has a//unique value. var keys:lazybidirectionalcollection<mapcollectionview<[key:value], key>> {get}//A collection Conta Ining just the values of ' self '//////values appear in the same order as they occur as the '. 1 ' member///K    Ey-value pairs in ' self '. var values:lazybidirectionalcollection<mapcollectionview<[key:value], value>> {get}}

You can see that the key of the dictionary must be the type that implements the Hashable protocol, i.e. the type of key is not limited to string!


1. Statement of the Dictionary

Define an empty dictionary var dic:[string:int]=[:]

Form:

var dicname:[key type: value type]


Or, use a pattern class to constrain its type

Dictionary pattern definition var mydic:dictionary<string,string>


2. Creation of dictionaries.


(1) We observe that the dictionary definitions given above can be seen with two init methods, which are two constructors that we can use to create a Dictionary object

Init ()
<span style= "font-family:arial, Helvetica, Sans-serif;" >init (Minimumcapacity:int) </span>
The second constructor specifies the minimum capacity of the dictionary

Using the init () constructor var mydic:[string:string]=dictionary<string,string> ()

Using init (Minimumcapacity:int) var dic2:[string:int]dic2=dictionary<string,int> (Minimumcapacity:5)


(2) Direct assignment create a dictionary


var mydic:dictionary<string,string>mydic=["Chinese": "99", "Mathematics": "100";

3. Empty operation of dictionaries or arrays


IsEmpty

Is the Boolean value returned with this property to determine whether the number of elements in the array or dictionary is 0


4. Accessing or modifying the elements of a dictionary


(1) The dictionary can be accessed directly by means of a key similar to the subscript, the element of the dictionary, and the variable dictionary defined by Var can be used to modify its value directly using key


var mydic:dictionary<string,string>mydic=["Chinese": "99", "Math": "];mydic[" Chinese "]=" 99.9222 "// Variable dictionaries can directly modify content println (mydic["language"])

Output:

Optional ("99.9222")

As you can see, by key we get an optional type that we need to parse because the value corresponding to the key may not exist!!!


(2) Resolve an optional type value


We must use an optional type to receive the value corresponding to the key, otherwise it will cause a compilation error

var yuwen:string? = mydic["Language"]

Complete Example:

var mydic:dictionary<string,string>mydic=["language": "99", "Math": "];mydic[", "Chinese"]= "99.9222"//variable dictionary can be directly modified Var yu: String? = mydic["Language"]if yu! = nil{    println (yu!)}

Output:

99.9222

As you can see, we parse the previous optional type into the normal type we need, and we can directly use the


5. Several ways to modify and add a dictionary element


(1) can be directly used subscript way, shape as

dic["key"] = value of the form to modify or add a dictionary element, if the key corresponding to the element does not exist will be added to the key value pair, otherwise it will directly modify the value corresponding to the key;


var mydic:dictionary<string,string>mydic=["Chinese": "99", "Math": "[]"];p rintln (mydic) mydic["2 Chinese"]= "99.9222" println (Mydic)


Output:

[Mathematics: 100, Chinese: 99] [Mathematics: 100, Chinese: 99, 2 languages: 99.9222]

The above key "2 language" does not exist in the original dictionary, this time will add an element, the corresponding key is the "2 language", the value is "99.922"


(2) How to use a dictionary


mutating func updatevalue (Value:value, Forkey key:key), value?

Examples of Use:

var mydic:dictionary<string,string>mydic=["language": "99", "Math": "[]"];p rintln (mydic) mydic.updatevalue ("888", Forkey: "New Key") println (Mydic)

Output:

[Mathematics: 100, Chinese: 99] [New key:888, Mathematics: 100, Chinese: 99]

As you can see, this method also adds a key-value pair to a nonexistent key, but if the key exists it will directly modify the value of the key.


6. Get all keys and values in the same way as in OC


To see the definition of a dictionary document, you can get all the keys and values by knowing the following two properties

    var keys:lazybidirectionalcollection<mapcollectionview<[key:value], key>> {get}//    A collection con  Taining just the values of ' self '//////    values appear in the same order as they occur as the '. 1 ' member//    of key-value pairs in ' self '.    var values:lazybidirectionalcollection<mapcollectionview<[key:value], value>> {get}

How to use:

var mydic:dictionary<string,string>mydic=["language": "99", "Math": "[]"];p rintln (mydic.keys) println (mydic.values)

Output:

Swift.LazyBidirectionalCollectionSwift.LazyBidirectionalCollection

You can see that the output is a collection type, and if we want to see its value, we can put it in the array:

var mydic:dictionary<string,string>mydic=["language": "99", "Math": "];var" keys1 = Array (Mydic.keys) println (KEYS1) var values1 = Array (mydic.values) println (values1)

Output, all keys values

[Maths, Chinese] [100, 99]


7. Several ways to delete a dictionary element


(1) Deleting a single array element

You can use Dic[key] = nil to delete an element

Or use the Removevalueforkey method to remove

var mydic:dictionary<string,string>mydic=["Chinese": "99", "Mathematics": "];mydic.removevalueforkey" ("Chinese") println ( Mydic) mydic["new"] = "println" (mydic) mydic["math"] = nilprintln (mydic)

[Math: 100] [Math: 100, added: 77] [Added: 77]


(2) Empty the dictionary element


var mydic:dictionary<string,string>mydic=["language": "99", "Math": "];mydic" = [:]println (Mydic)

Assign the dictionary directly to null


Mydic = [:] Can


Or:

var mydic:dictionary<string,string>mydic=["Chinese": "99", "Math": "];mydic.removeall" (Keepcapacity:false) println (Mydic)

For Keepcapacity:false/true, according to the needs of choice can;

The difference is true, will keep the data capacity, Occupy space?


8. Copy of the Dictionary


Dictionary replication laws and arrays are similar


If the element in the dictionary is a value type, such as an integer, then the dictionary copies the source dictionary out of the copy of the element, and if the element in the dictionary is a reference type, such as an object, then when the dictionary is copied, only the pointer to the element is copied, and the pointer modifies the contents of the source dictionary.

For swift arrays See http://blog.csdn.net/yangbingbinga/article/details/44747877


More Swift Tutorials: Http://blog.csdn.net/yangbingbinga







Swift Tutorial 13-Dictionary dictionary and Nsdictionary

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.