Swift5.0 数组(Array), 字典(Dictionary)详解

1.数组(Array)

var array = [1, 5, 3, 8, 12, 6, 20] // 创建数组
array.sort() // 升序  结果: [1, 3, 5, 6, 8, 12, 20]
array.sort { (obj1, obj2) -> Bool in
    return obj1 > obj2
} // 降序  结果: [20, 12, 8, 6, 5, 3, 1]
array.append(45) // 追加元素  结果: [1, 5, 3, 8, 12, 6, 20, 45]
array.reverse() // 反转  结果: [20, 6, 12, 8, 3, 5, 1]
array.remove(at: 0) // 根据下标删除元素  结果: [5, 3, 8, 12, 6, 20]
array.removeAll() // 删除全部元素  结果: []
array.removeLast() // 删除最后一个元素  结果: [1, 5, 3, 8, 12, 6]
array.removeFirst() // 删除第一个元素  结果: [5, 3, 8, 12, 6, 20]
array.removeLast(2) // 从后面删除几个元素  结果: [1, 5, 3, 8, 12]
array.removeFirst(2) // 从前面删除几个元素  结果: [3, 8, 12, 6, 20]
array.isEmpty // 是否为空  结果: false
array.count // 数组长度  结果: 7
array = array.filter { $0 != 5 } // 过滤  结果: [1, 3, 8, 12, 6, 20]
array.insert(100, at: 2) // 在下标的位置插入元素  结果: [1, 5, 100, 3, 8, 12, 6, 20]
array[0] = 50 // 修改下标对应的元素  结果: [50, 5, 3, 8, 12, 6, 20]

// ①数组相加
let array1: [String] = ["2", "3"]
let array2: [String] = ["4", "5"]
let array3 = array1 + array2
print(array3)
// ["2", "3", "4", "5"]

// ②数组相加
var array1: [Any] = ["2", "3"]
let array2: [Any] = ["4", "5"]
array1.append(array2)
print(array1)
// ["2", "3", ["4", "5"]]

2.字典(Dictionary)

  • 基本用法
var interestingNumbers = ["Prime" : [2, 3, 5, 7, 11, 13],
                          "Fibonacci": [1, 1, 2, 3, 5, 8],
                          "Square": [1, 4, 9, 16, 25]] // 创建字典
interestingNumbers["Jayne"] = [13] // 追加元素  结果:["Prime": [2, 3, 5, 7, 11, 13], "Square": [1, 4, 9, 16, 25], "Jayne": [13], "Fibonacci": [1, 1, 2, 3, 5, 8]]
interestingNumbers["Prime"] = [45] // 修改元素  结果:["Prime": [45], "Square": [1, 4, 9, 16, 25], "Fibonacci": [1, 1, 2, 3, 5, 8]]
interestingNumbers.removeAll() // 删除全部元素  结果:[:]
interestingNumbers.removeValue(forKey: "Prime") // 删除key  结果:["Fibonacci": [1, 1, 2, 3, 5, 8], "Square": [1, 4, 9, 16, 25]]
let value = interestingNumbers["Prime"] // 查询 Prime 对应的值  结果:Optional([2, 3, 5, 7, 11, 13])
let count = interestingNumbers.count // 获取字典长度  结果:3
for (kind, numbers) in interestingNumbers {
    print(kind, numbers, separator: ":", terminator: " ")
} // 遍历  结果:Prime:[2, 3, 5, 7, 11, 13] Fibonacci:[1, 1, 2, 3, 5, 8] Square:[1, 4, 9, 16, 25]
  • 字典合并
// 创建一个扩展
extension Dictionary {
    /// 合并字典
    ///
    /// - Parameter dict: 要合并的字典
    mutating func merge(dict: [Key: Value]) {
        for (key, value) in dict { // 遍历
            self[key] = value
        }
    }
}

// 示例
var interestingNumbers = ["Prime" : [2, 3, 5, 7, 11, 13],
                         "Fibonacci": [1, 1, 2, 3, 5, 8],
                         "Square": [1, 4, 9, 16, 25]] // 创建字典
let interestingNumbersTemp = ["Student" : [2, 3],
                          "Person": [1, 8]] // 创建字典

interestingNumbers.merge(dict: interestingNumbersTemp)
print(interestingNumbers)
// ["Prime": [2, 3, 5, 7, 11, 13], "Fibonacci": [1, 1, 2, 3, 5, 8], "Person": [1, 8], "Square": [1, 4, 9, 16, 25], "Student": [2, 3]]

你可能感兴趣的:(Swift5.0 数组(Array), 字典(Dictionary)详解)