概述
在了解正式内容之前可以先回顾下objectiveC中提供的集合特性。
它的特点是,拿NSArray举例,包含NSArray 和 NSMutableArray两个API,前者是不可变数组,一旦创建其值和数量就不能改变了;NSMutableArray是可变数组,继承了NSArray,数组对象相当于java中的list(有序集合),这里的有序是指放入的顺序,并不是数据真实的排序。NSArray数组对象的索引也是从0开始的。
那么Swift的集合就简单的多了,如下:
它也有可变和不可变之分,但是是用var或let
来决定的。
集合详解
数组Array
数组是值的有序集合,任何值都可以在数组中出现多次。数组通常用于值的有序很重要或者很有用的场合,但是值的顺序是否有意义并不是先决条件。与Objective-C不同的是,Swift的Array类型可以持有任何类型的值(对象和非对象都可以),而Objective-C的数组只能存储对象类型,基本类型需要用[]这种方式存放。
同样的可变和不可变由var或let来决定。
创建数组
以下三种定义等价的,这种有点类似于java的实现方法。
//这种方式比较直观,个人比较推荐。可能和笔者从事多年java开发养成的习惯吧。
var bucketList: Array<String> = ["Climb Mt. Everest"]
var bucketList1:[String] = ["Climb Mt. Everest"]
var bucketList2 = ["Climb Mt. Everest"]
数组操作
包括索引和追加等操作。
import Foundation
// Mutable arrays
var bucketList = ["1"]
var newItems = ["2", "3", "4", "5", "6"]
//相加 ~~ bucketList = ["1", "2", "3", "4", "5", "6"]
bucketList += newItems
//删除:按索引删除单个元素,返回 3,当前bucketList = ["1", "2", "4", "5", "6"]
bucketList.remove(at: 2)
//长度 5
print(bucketList.count)
//取值:区间取值 2,4, 5
print(bucketList[1...3])
//修改:修改某个元素的值,此时索引为2的元素由4变成 4 7
bucketList[2] += " 7"
//插入:插入一个值
bucketList[0] = "8"
//插入:插入一个值,此时bucketList = ["8", "2", "9", "4 7", "5", "6"]
bucketList.insert("9", at: 2)
//追加, bucketList = ["8", "2", "9", "4 7", "5", "6", "10"]
bucketList.append("10")
//可变数组
var myronsList = [
"Climb Mt. Kilimanjaro",
"Fly hot air balloon to Fiji",
"Toboggan across Alaska",
"Go on a walkabout in Australia",
"Scuba dive in the Great Blue Hole",
"Find a triple rainbow"
]
//判断相等,false
let equal = (bucketList == myronsList)
//不可变数组
let lunches = ["Cheeseburger",
"Veggie Pizza",
"Chicken Caesar Salad",
"Black Bean Burrito",
"Felafel wrap"
]
字典Dictionary
字典是一个比较经典的设计,每种编程语言中都有,它是一种键值对存储的结构,其key可以是string、int、float甚至bool。 其语法:var dict: Dictionary<Key, Value>。下列的实现方式都是合理。
创建字典
var dict1: Dictionary<String, Double> = [:]
var dict2 = Dictionary<String, Double>()
var dict3: [String:Double] = [:]
var dict4 = [String:Double]()
字典操作
主要包括增加、修改、删除和遍历几种
var movieRatings = ["Donnie Darko": 4, "Chungking Express": 5, "Dark City": 4]
//字典长度 ~~ I have rated 3 movies.
print("I have rated \(movieRatings.count) movies.")
//读取:取值 ~~4
let darkoRating = movieRatings["Donnie Darko"]
//修改:修改或添加新值~~5
movieRatings["Dark City"] = 5
//修改:这种方法会返回老的值 ~~ Old rating: 4; current rating: 5
let oldRating: Int? = movieRatings.updateValue(5, forKey: "Donnie Darko")
if let lastRating = oldRating, let currentRating = movieRatings["Donnie Darko"] {
print("Old rating: \(lastRating); current rating: \(currentRating)")
}
//删除,下面两种方法等价,只不过=nil不会返回被删除元素的值
let removedRating: Int? = movieRatings.removeValue(forKey: "Dark City")
movieRatings["Dark City"] = nil
//遍历,ENTRY,只输出The movie Donnie Darko was rated: 5.和The movie Chungking Express was rated: 5.
for (key, value) in movieRatings {
print("The movie \(key) was rated: \(value).")
}
//遍历, key和value
for movie in movieRatings.keys {
print("User has rated \(movie).")
}
for movie in movieRatings.values {
print("User has rated \(movie).")
}
//dict 与 Array
let watchedMovies = Array(movieRatings.keys)
let georgia = ["Cobb": [30301,30302,30303,30304,30305],
"Dekalb": [30306,30307,30308,30309,30310],
"Fulton": [30311,30312,30313,30314,30315]
]
var zipcodes: [Int] = []
for zipcodeArray in georgia.values {
for zipcode in zipcodeArray {
zipcodes.append(zipcode)
}
}
//Georgia has the following zip codes: [30306, 30307, 30308, 30309, 30310, 30301, 30302, 30303, 30304, 30305, 30311, 30312, 30313, 30314, 30315]
print("Georgia has the following zip codes: \(zipcodes)")
集合Set
这个没啥好说的,它存储的是值,并且值不能重复。
创建集合
大概有下列三种创建集合的方法。
var groceryBag = Set<String>()
//直接初始化
var groceryBag = Set(["Apples", "Oranges", "Pineapple"])
//这种写法借鉴了Array
var groceryBag:Set = ["Apples", "Oranges", "Pineapple"]
常规操作
常归的增加、删除、查询操作;
var groceryBag = Set<String>()
//插入:
groceryBag.insert("Apples")
groceryBag.insert("Oranges")
groceryBag.insert("Pineapple")
//查询
let hasBananas = groceryBag.contains("Bananas")
//遍历
for food in groceryBag {
print(food)
}
集合操作
它还有集合所特有的交集、并集等操作
var groceryBag:Set = ["Apples", "Oranges", "Pineapple"]
//合并两个不同的集合
let friendsGroceryBag = Set(["Bananas", "Cereal", "Milk", "Oranges"])
//{"Oranges", "Apples", "Milk", "Pineapple", "Bananas", "Cereal"}
let commonGroceryBag = groceryBag.union(friendsGroceryBag)
//求两个集合的交集
let roomatesGroceryBag = Set(["Apples", "Bananas", "Cereal", "Toothpaste"])
//{"Cereal", "Apples", "Bananas"}
let itemsToReturn = commonGroceryBag.intersection(roomatesGroceryBag)
//不相交,判断两个集合是否有值相同,如果有任意的一个值相同则返回false
let yourSecondBag = Set(["Berries", "Yogurt"])
let roommatesSecondBag = Set(["Grapes", "Honey"])
//true
let disjoint = yourSecondBag.isDisjoint(with: roommatesSecondBag)