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.countdict.isEmptyArray(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"] = nildict.removeAll()for key in dict.keys { print(key)}for (key,value) in dict { print("/(key):/(value)")}
新闻热点
疑难解答