字典以键值对的形式存储数据。
键不能重复,但是值可以重复。
基本语法用例:
var states : Dictionary<String, String> = ["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 values for (key, value) in states { print("State name = \(value), abbreviation = \(key)") } // iterate keys for abbreviation in states.keys { print("Abbreviation = \(abbreviation)") } // iterate values for name in states.values { print("Name = \(name)") }
时间: 2024-10-27 02:29:34