简介
- 一组同类型的值的组合, 根据组合的整体特性分为:
- 有序可重复 - 数组(Array)
- 无序不重复 - Set
- 无序可重复,但每个值有唯一的键(Key) - 字典(Dictionary)
- 批量处理集合中的元素, 可以使用 for in循环
数组
- 定义: Array<类型> 或 [类型]
let array: [Int]
let array2: Array<Int>
array = [Int](repeatElement(3, count: 10))
- 创建一个有序范围的Int数组,Array(起始值...终止值)
let array2 = Array(1...10)
- 用数组字面量来创建数组: [值1, 值2, 值3, ..., 值N]
var places = ["beijing","shanghai","guangzhou","shenzhen"]
- 元素计数:count, 空否: isEmpty
places.count
places.isEmpty
- 添加: append, 添加一个同类型数组 +=
places.append("wuhan")
let haiwaiPlace = ["NewYork","London","Sao paolu"]
places += haiwaiPlace
- 获取元素 : 数组名[索引], ⚠️索引总是从0开始
places.count
places[7]
print(places.count)
print("\(places.startIndex), \(places.endIndex)")
//注意* endIndex 是数组的长度,places[places.endIndex]会越界
- 插入: insert
var arr = [1, 2, 3, 6, 5, 2]
arr.insert(0, at: 4) //插入一个元素
arr.insert(contentsOf: [0,0,0,0], at: 0) //插入一个集合
- 移除: remove
places.remove(at: 8) //移除指定位置
places.removeAll() //移除所有
places.removeSubrange(0 ... 1) //移除指定范围
*数组排序
var arr = [1, 2, 3, 6, 5, 2]
print(arr)
let arr2 = arr.sorted { (a, b) -> Bool in
return b < a //如果b<a就置换顺序,代表从大到小排列
}
print(arr2)
*数组遍历
//遍历数组元素
for item in array5 {
print(item)
}
//遍历数组元素和索引
for (index,item) in array5.enumerated() {
print(index,item)
}
集合
- 定义: Set<元素类型>, 无法使用类型推断,但可省略类型.
var cardno : Set = [1,2,3]
- 用数组字面量创建集合
var citys : Set = ["Shanghai","Beijing","wuhan","Hef"]
- 元素计数: count, 空否: isEmpty
citys.count
cardno.isEmpty
- 插入:insert
citys.insert("guangzhou")
- 移除:remove
citys.remove("Shanghai")
- 是否包含某元素:contains
citys.contains("Beijing")
- 转换为数组:sorted
let cityArray = citys.sorted()
集合间的运算: 交差并补
- 交集 intersection,formIntersection
var x :Set = [1,2,3,4]
let y :Set = [3,4,5,6]
//x,y值不变,返回新值
x.intersection(y)
//x值改变为原xy的交集
x.formIntersection(y)
- 差集 subtract,subtracting
//x移除y,无返回值
x.subtract(y)
//h、i值不变,返回一个新的set
let j = h.subtracting(i)
- 并集 union,formUnion
//x,y值不变,返回新的set合集
x.union(y)
//i合并到h里
h.formUnion(i)
- 补集 symmetricDifference,formSymmetricDifference
x.symmetricDifference(y)
集合间的关系
- 相等: 两个集合有完全相同的元素.
let h : Set = [1,2,3]
let i : Set = [3,2,1,4]
h == i
- 子集: isSubset(可以相等), 严格子集isStrictSubset
h.isSubset(of: i)
h.isStrictSubset(of: i)
- 父集: isSupersetOf(可以相等), 严格父集isStrictSuperSetOf
i.isSuperset(of: h)
i.isStrictSuperset(of: h)
- 无交集: isDisjoint
let j : Set = ["游戏","动漫"]
let k : Set = ["购物","小吃","化妆"]
j.isDisjoint(with: k)
字典
字典: 值无序可重复,但每个值有唯一的键(Key)
定义: Dictionary<键类型, 值类型>, 或 [键类型: 值类型]
var a: Dictionary<String,String>
var b: [String:String]
var airports = ["PVG":"Shanghai Pudong", "CHU":"Dalian", "DUB":"Dublin Airport"]
- 计数: count, 空否: isEmpty
airports.count
airports.isEmpty
- 添加或更新: 字典变量[键] = 值
airports["SHQ"] = "Hongqiao Airport"
airports["CHU"] = "大连周水子机场"
- 获取,依然可以用下标
airports["SHQ"]
- 移除,用下标把值设为nil
airports["DUB"] = nil
- 循环一个字典 for in, 因为键值对有2个元素, 用元组变量.
for (key, value) in airports {
print(key,value)
}
- 把键值对分离成数组,用 [数组类型] (字典变量.keys), [数组类型] (字典变量.values)
let codes = [String](airports.keys)
网友评论