本文共 750 字,大约阅读时间需要 2 分钟。
字典以键值对的形式存储数据。
键不能重复,但是值可以重复。
基本语法用例:
var states : Dictionary= ["CA" : "California"]var states : [String : String] = ["CA" : "California"]
也可以使用类型推断的方式:
var states = ["CA" : "California"]var states = ["CA" : "California", "NV" : "Nevada", "OR": "Oregon", "AZ" : "Arizona"]
修改键值:
states["NV"] = "Nevada"
或者
states.updateValue("State of Nevada", forKey: "NV")
访问键值:
let value = states["NV"]
删除键值:
states["TX"] = nil// 或者states.removeValueForKey("TX")
遍历键值对:
// iterate keys and valuesfor (key, value) in states { print("State name = \(value), abbreviation = \(key)")}// iterate keysfor abbreviation in states.keys { print("Abbreviation = \(abbreviation)")}// iterate valuesfor name in states.values { print("Name = \(name)")}
转载地址:http://lswno.baihongyu.com/