Swift dictionary nsdictionary definition, modifier key value, delete/Add key value

Source: Internet
Author: User
Tags modifier
// Playground-noun: a place where people can play

import UIKit

// ------------------------------------------------ ------------------------------
// 1. Define a fixed-format dictionary
// All "key value" types of dict1 are consistent (both strings)
var dict1 = ["name": "mary", "age": "18"]

// ------------------------------------------------ ------------------------------
// 2. In the definition dictionary, you can directly specify the type of "key name" and "key value" in the dictionary
// Once the dictionary's key name and key value type are specified, it can no longer be modified
var ages: Dictionary <String, Int> = ["jack": 20, "rose": 19]

// ------------------------------------------------ ------------------------------
// 3. Dictionary operations
// Can be directly operated for fixed-format dictionaries
// 1> Get the dictionary key value by key value. Since the dictionary format is fixed, there is no need to specify the variable type
// *** Note that the operation results specified by the "Specify / Cancel" value type are different
var name = dict1 ["name"] // as String
name = "mike" + "\ (name)"

// *** Because you may get a nil when getting a value from a dictionary, you need to judge if you need to process the data later
if var age = dict1 ["age"] ?. toInt () {
    age + = 20
}

// 2> Two ways to modify dictionary keys
dict1 ["name"] = "rose"
dict1
dict1.updateValue ("18", forKey: "age")
dict1

// 3> delete a certain key value
dict1.removeValueForKey ("age")
dict1

// 4> add new key-value pairs
dict1 ["height"] = "1.65"
dict1  

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.