Tuesday, July 1, 2014

Dictionaries

Dictionaries

Dictionary<KeyType, ValueType>

var pitchers = [
    "Wang": 40,
    "Kuo": 56,
]

Add new item
pitchers["Chen"] = 16

//pitchers =["Kuo": 56, "Wang": 40, "Chen": 16]

println("There are \(pitchers.count) pitchers in the dictionary.")
//Console output: There are 3 pitchers in the dictionary.

Change item value

pitchers["Kuo"] = 00

//pitchers =["Kuo": 0, "Wang": 40, "Chen": 16]

for loop: Iterating Over the dictionary

for (surname, number) in pitchers {
    println("\(surname): \(number)")
}

//Console output: 
Kuo: 0
Wang: 40
Chen: 16

for surname in pitchers.keys {
    println("Pitcher Surname: \(surname)")
}

for number in pitchers.values {
    println("Pitcher Number: \(number)")
}

//Console output:
Pitcher Surname: Kuo
Pitcher Surname: Wang
Pitcher Surname: Chen
Pitcher Number: 0
Pitcher Number: 40
Pitcher Number: 16

================================

Declare an empty dictionary
var airlineCode = Dictionary<String, String>()

println("There are \(airlineCode.count) data.")

var airlineCode = [String: String]()


//Console output: There are 0 data.
//The first line may be written as the shortcut format var airlineCode = [String: String]()

Add new item
airlineCode["EVA Air"] = "BR"
//airlineCode = ["EVA Air": "BR"]

Reset the dictionary
airlineCode = [:]

No comments:

Post a Comment