集合基本类型:数组 Array (有序), 集合 Set (无序不重复), 字典 Dictionary (无序键值对)
1.数组 Arrays
(1)数组的表示
Array<Element> [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<Element>
(2)构造一个集合
var letters = Set<Character>() //或 letters.insert("a") letters = []
(3)字面量创造集合
var fav: Set<String> = ["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 = [" 标签:Set,airports,List,iOS,fav,var,let,集合,Swift From: https://www.cnblogs.com/lysboke/p/17652641.html