美文网首页
Swift 3.0学习笔记_7_字典

Swift 3.0学习笔记_7_字典

作者: henu_Larva | 来源:发表于2017-04-25 14:12 被阅读1次
//字典是一种存储多个相同类型的值得容器,每个值(value)都关联唯一的键(key),键作为字典中的这个值数据的标识符.字典中的数据没有具体顺序.
//Swift 的 Dictionary 类型已被桥接到 OC-Foundation 的 NSDictionary 类.

//1.字典类型简化语法
//Swift 的字典使用 Dictionary<Key,Value>定义,其中 Key 是字典中键的数据类型, Value 是字典中对应于这些键所存储值得数据类型
//我们也可以采取 [Key:Value] 这样的简化形式去创建一个字典类型.推荐使用这种形式.

//2.创建一个空字典
var namesOfIntegers = [Int:String]()
//namesOfIntegers 是一个空的 [Int:String]字典,它的键是 Int 类型,值是 String 类型

//如果上下文已经提供了类型信息,我们可以使用空字典字面量来创建一个空字典,记作 [:].
namesOfIntegers[16] = "sixteen"
namesOfIntegers = [:]

//3.用字典字面量创建字典
var airports:[String:String] = ["YYZ":"Toronto Pearson","DUB":"Dublin"]
//简写
var airports2 = ["YYZ":"Toronto Pearson","DUB":"Dublin"]

//4.访问和修改字典
//可以通过 count 属性获取字典的数据项数量
let dicCount = airports.count
//可以通过 isEmpty 属性去检测 count 属性是否为 0
if airports.isEmpty {
    print("is empty")
} else {
    print("not empty")
}
//通过下标语法添加或修改数据项
airports["LHR"] = "London"
airports["LHR"] = "Lonton Heathrow"

//updateValue(_:forKey)方法可以设置或更新特定键对应的值,当这个键不存在对应值的时候会设置新值或者在存在时更新已存在的值.updateValue(_:forKey)方法返回更新值之前的原值,这样可以使得我们可以检测是否更新成功
//updateValue(_:forKey)方法会返回对应值得类型的可选值.
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
    print("\(oldValue)")
} else {
    print("123")
}

//可以使用下标语法在字典中检索特定键对应的值,因为有可能请求的键没有对应的值存在,字典的下标访问会返回对应值得类型的可选值.如果这个字典包含请求键所对应的值,下标会返回一个包含这个存在值得可选值,否则返回 nil
if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}

//可以使用下标语法来通过给某个键的对应值赋值为 nil 来从字典里移除一个键值对
airports["APL"] = "Apple Internation"
airports["APL"] = nil //"APL"被移除

// removeValue(forKey:)方法也可以用来在字典中移除键值对,该方法在键值对存在的情况下会移除该键值对并返回被移除的值或者在没有值的情况下返回 nil
if let removedValue = airports.removeValue(forKey: "DUB") {
    print("The removed airport's name is \(removedValue).")
} else {
    print("The airports dictionary does not contain a value for DUB.")
}

//5.字典遍历
for (airportCode,airportName) in airports {
    print("\(airportCode): \(airportName)")
}
//遍历 Key
for airportCode in airports.keys {
    print("Airport code: \(airportCode)")
}
//遍历 Value
for airportName in airports.values {
    print("Airport name: \(airportName)")
}

//如果我们只是需要使用某个字典的键集合或者值集合来作为某个接受 Array 实例的 API 的参数,可以直接使用 keys 或者 values 属性构造一个新的数组
let airportCodes = airports.keys
let airportNames = airports.values

相关文章

网友评论

      本文标题:Swift 3.0学习笔记_7_字典

      本文链接:https://www.haomeiwen.com/subject/iwsvzttx.html