技术文章分类(180)

技术随笔(11)

swift的语法小demo7(字典,dictionary)

 

//
//  main.swift
//  SwiftGrammarStudy
//
//  Created by dongway on 14-6-6.
//  Copyright (c) 2014年 dongway. All rights reserved.
//

import Foundation

/*
    字典
*/
var airports: Dictionary<String, String> = ["TYO": "Tokyo", "DUB": "Dublin"]
println("The dictionary of airports contains \(airports.count) items.")
// prints "The dictionary of airports contains 2 items.”
airports["LHR"] = "London"
// the airports dictionary now contains 3 items”
airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed to "London Heathrow”
//修改值
if let oldValue = airports.updateValue("Dublin International", forKey: "DUB") {
    println("The old value for DUB was \(oldValue).")
}
// prints "The old value for DUB was Dublin.”
if let airportName = airports["DUB"] {
    println("The name of the airport is \(airportName).")
} else {
    println("That airport is not in the airports dictionary.")
}
//删除键值对
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.")
}

//迭代
for (airportCode, airportName) in airports {
    println("\(airportCode): \(airportName)")
}
// TYO: Tokyo
// LHR: London Heathrow”
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”

//取出某个字段所有数据(个人觉得很有用)
let airportCodes = Array(airports.keys)
// airportCodes is ["TYO", "LHR"]

let airportNames = Array(airports.values)
// airportNames is ["Tokyo", "London Heathrow"]”

var namesOfIntegers = Dictionary<Int, String>()
// namesOfIntegers is an empty Dictionary<Int, String>”
namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type Int, String”

 

posted @ 2014-06-12 11:37  坤哥MartinLi  阅读(245)  评论(1编辑  收藏  举报