Swift--Dictionary

Source: Internet
Author: User
Swift--Dictionary

1. Create an empty dictionary

Way One:

var dic1 = [int:string] () the type of the//key is Int and the type of value is String

Way two:

var dic2 = dictionary<sting,int> ()//key is of type Sting

2. Create a dictionary with literal amounts

var dic3:dictionary<int,string> = [1: "A", 2: "B", 3: "C"]

3. Get the number of elements

Print (Dic3.count)

4. Is the empty

Print (Dic3.isempty)

5. Get the value

Print (dic3[2]!) ! Convert optional Types

6. Change the value

DIC3[2] = "ABC"

7. Delete a value

Way One:

DIC3[2] = nil//Because the element in the dictionary is an optional type, it can be nil directly

Way two:

Dic.removevalueforkey (2)

8. Traversing a dictionary

Way One:

For KV in dic3{

Print (KV)//Tuple format:(1, "a")

}

Way two:

for (Mkey,mvalue) in dic3{

Print (Mkey,mvalue)

}

9. Ordered output of the dictionary (small-to-large)

For key in Dic3.keys.sort () {

Print (Key,dic3[key])

}

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.