集合基本类型:数组 Array (有序), 集合 Set (无序不重复), 字典 Dictionary (无序键值对)
1.数组 Arrays
(1)数组的表示
Array
[Element]
(2)创建空数组
var someInts: [Int] = []
someInts.count //数组长度
(3)带值数组
var a = Array(repeating: 0.0, count:3) //[0.0, 0.0, 0.0]
//repeating:初始值.count:长度
(4)两数组相加创建数组
var a = Array(reapeating: 0.0, count = 3)
var b = Array(reapeating: 2.5, count = 3)
var c = a + b //[0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
(5)字面量创造数组
var List: [String] = ["Eggs", "Milk"] //或者
var List = ["Eggs", "Milk"]
(6)访问数组
List.count //长度(数据量)
List.isEmpty //是否为空
List[0] //Eggs
var egg = List[0] //将第一个数组的值赋给egg
(7)添加
List.append("Flour") //append()方法添加
List += ["Powder"] //直接添加一个数据
List += ["Spread", "Cheese", "Butter"] //直接添加多个数据
List.insert("up", at: 0) //在第一个数据前添加"up"
(8)修改
List[0] = "Six Eggs"
List[4...6] = ["Banana", "Apple"]
(9)删除
let a = List.remove(at: 0) //索引值为0的项被移除。a被赋值被删除的那一项的值。后边的项自动往前补
let apple = List.removeLast() //移除最后一项,a被赋值被删除的那一项的值
(10)遍历
for item in List{
print(item)
}
同时需要索引和值时:
for (index,value) in List.enumerated(){
print( "Item \( String(index + 1) ): \(value)" )
}
2.集合 Sets
(1)集合的表示
Set
(2)构造一个集合
var letters = Set() //或
letters.insert("a")
letters = []
(3)字面量创造集合
var fav: Set = ["Rock", "Class", "Hip"] //或
var fav: Set = ["Rock", "Class", "Hip"]
(4)访问
fav.count //长度
fav.isEmpty //是否为空
fav.contains("Funk") //检查是否包含"Funk"值
(5)添加
fav.insert("Jazz")
(6)删除
fav.remove("Rock") //如果有这个值则返回这个值,如果没有则返回nil
fav.removeAll()
(7)遍历
for g in fav{
print("\(g)")
}
//返回一个有序数组
for g in fav.sorted(){
print("\(g)")
}
(8)集合操作
let add: Set = [1, 3, 5, 7, 9]
let even: Set = [0, 2, 4, 6, 8]
let single: Set = [2, 3, 5, 7]
add.union(even).sorted() //[] 交集
add.intersection(even).sorted() //[1, 9] add不在single中的值的集合
add.symmetricDifference(single).sorted() //[1, 2, 9] add和single不相交的值
(9)集合关系
let h: Set = ["", ""]
let f: Set = ["", "", ""]
let c: Set = [""]
//==: 全部相同
h.isSubset(of: f) //true h是否被f全包
f.isSuperset(of: h) //true f是否全包h
f.isDisjoint(with: c) //true f,c是否无交集
//isStrictSubset(of: ) / isStrictSuperSet(of: ) A是否是B的子集或父集且AB不相等
3.字典 Dictionary
(1)字典的表示
Dictionary 或者 [Key: Value]
(2)创建空字典
var names: [Int: String] = [ : ] //或者
names[16] = "sixteen"
names = [ : ]
(3)字典字面量创建字典
var airports: [String: String] = ["a": "1", "b": "2"] //或者
var airports = ["a": "1", "b": "2"]
(4)访问
airports.count //数量
airports,isEmpty //是否为空
(5)新增
airports["c"] = "3"
(6)修改
airports["c"] = "4"
(7)更新
airports.updateValue("6", forkey: "a")
//如果forkey存在值则修改,返回修改前的值。不存在则返回nil
(8)检索键对应的值。无值则返回nil
airName = airports["a"]
(9)移除键值对
airports["a"] = nil //或者
airports.removeValue(forkey: "a") //存在时返回被移除的值,不存在时返回nil
(10)遍历
//1
for (airCode, airName) in airports{
print("\(airCode) : \(airName)")
}
//2
for airCode in airports.keys{
print("code: \(airCode)")
}
//3
let airCodes = [String](airports.keys)
let airNames = [String](airports.values)