Swift包含三种集合类
- 数组 Array
- 字典 Dictionary
- 集合 Set
数组
// 数组的声明 (调用数组的构造函数)
var numbers:[Int] = [1,2,3,4]
var strings:[String] = ["one","two","three","four"]
// 空数组的声明
var emptyArray1:[Int] = []
var emptyArray2 = [Int]()
var emptyArray3 = Array<Int>()
var emptyArray4:[String] = []
var allZero = [Int](repeatElement(0, count: 5))
allZero.count // 数量
allZero.isEmpty // 是否为空
allZero[2] // 去下标值
allZero.first // 第一个元素
allZero.last // 最后一个元素
numbers[1..<3] // 取子数组
numbers.min() //最小值
numbers.max() //最大值
strings.max() //String 排序有点蒙
strings.min()
strings.contains("one") // 是否包含元素
strings.contains("five")
strings.index(of: "one") // 元素在数组的位置
strings.index(of: "two") // 元素在数组的位置
strings.index(of: "five") // 返回的是一个可选型
if let firstValue = allZero.first {
print("the first value is " + String(firstValue))
}
数组的增 删 改
var strings:[String] = ["one","two","three","four"]
// 改
strings[0] = "1"
strings[1...3] = ["2","3","4"]
// 增
strings.append("five")
strings += ["six"]
strings.insert("seven", at: 3)
// 删
strings.removeLast()
strings.removeFirst()
strings.remove(at: 2)
strings.removeSubrange(0..<1)
strings.removeAll()
数组的遍历
// 数组的声明 (调用数组的构造函数)
var numbers:[Int] = [1,2,3,4]
var strings:[String] = ["one","two","three","four"]
for number in numbers {
print(number)
}
for index in 0..<numbers.count {
print(numbers[index])
}
for (i,number) in numbers.enumerated() {
print("i is " + String(i) + " value is " + String(number))
字典的增删改查
var dict = ["key":"value","key1":"value1"]
var dict1 = ["key":"value","key1":1] as [String : Any]
var dict2:Dictionary<String,Any> = ["key":"value","key1":"value1"]
var dict3:[String:Any] = ["key":"value","key1":"value1"]
dict.count
dict.isEmpty
Array(dict1.values)
Array(dict.keys)
// 改
dict["key"] = "value0"
dict.updateValue("value0", forKey: "key")
// 增
dict["key3"] = "value3"
dict.updateValue("value4", forKey: "key4")
//删
dict.removeValue(forKey: "key4")
dict["key"] = nil
dict.removeAll()
for key in dict.keys {
print(key)
}
for (key,value) in dict {
print("\(key):\(value)")
}