玖叶教程网

前端编程开发入门

「Swift 3.1笔记」05-字典(Dictionary)

自从苹果2014年发布Swift,到现在已经两年多了,而Swift也来到了3.1版本。最近利用工作之余,把官方的Swift编程指南看了一遍。现在整理一下笔记,回顾一下以前的知识,有需要的同学可以去看Swift官方文档。

字典(Dictionary)

1、定义一个可变字典

var dict1 : [String : NSObject] = [String : NSObject]()

2、定义一个不可变字典,同时进行初始化

let dict2:[String : Any] = ["name" : "why", "age" : 18]

3、创建一个空字典

var namesOfIntegers = [Int: String]()

4、如果上下文已经提供了类型信息,可以使用[:]来创建一个空字典

namesOfIntegers[16] = "sixteen"

namesOfIntegers = [:]

var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

5、判断字典中键值对的个数是否为0:

if airports.isEmpty {

print("The airports dictionary is empty.")

} else {

print("The airports dictionary is not empty.")

}

6、使用下标语法添加新的键值对:

airports["LHR"] = "London Heathrow"

还可以使用updateValue(_:forKey:)方法来设置或更新一个键对应的值,并返回一个可选类型的值

iflet oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {

print("The old value for DUB was \(oldValue).")

}

7、使用下标语法来获取键对应的值:

iflet airportName = airports["DUB"] {

print("The name of the airport is \(airportName).")

} else {

print("That airport is not in the airports dictionary.")

}

8、使用下标语法并把键对应的值设置为nil来删除一个键值对:

airports["APL"] = "Apple International"

airports["APL"] = nil

另外,还可以使用removeValue(forKey:)方法来删除一个键值对,如果存在,返回键对应的值;如果不存在,返回nil:

iflet 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.")

}

9、字典的遍历

(1)遍历整个字典 (Iterating Over a Dictionary)

for (airportCode, airportName) in airports {

print("\(airportCode): \(airportName)")

}

(2)使用keys和values属性来遍历字典的所有键和所有值:

for airportCode in airports.keys {

print("Airport code: \(airportCode)")

}

for airportName in airports.values {

print("Airport name: \(airportName)")

}

更多精彩内容,请关注爱恨的潮汐微信公众号(微信ID:xueyuanxunmeng)

营运人员:爱恨的潮汐

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言