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)")}
新聞熱點
疑難解答