【学习】重学Swift5-集合类

四、集合类

1.数组

  1. 初始化

    // 字面量初始化 
    let array = [1, 2, 3, 4]
    // 创建空数组必须携带类型信息
    let intArr:[Int] = []
    var stringArr:[String] = []
    array = []
    
    // 使用初始化器
    var myArr = [String]()
    var myArr2 = Array<String>()
    
    let fiveZs = Array(repeating: "Z", count: 5)
    
    let numbers = [Int](0...7)
    let persons = ["zhangsan":27, "lisi":28, "wangwu":29]
    let names = [String](persons.key)
    
    // decoder
    
  2. 遍历、索引、查找

    // 使用count获取个数,isEmpty判断是否为空
    persons.count
    persons.isEmpty
    
    // 只能得到值
    for-in 上面已有尝试
    forEach
    while + Iterator
    // 同时得到索引和值
    enumerated()
    
    let numbers = [Int](2...7)
    numbers.forEach { (num) in
        // break continue 不能在ferEach中使用,return只会跳出当前但不打断forEach循环
        if num == 3 {
    //        break
    //        continue
            return
        }
        print(num)
    }
    
    for (index, num) in numbers.enumerated() {
        print(index,num)
    }
    
    var it = numbers.makeIterator()
    while let num = it.next() {
        print(num)
    }
    
    // startIndex和endIndex类似于字符串,但不同于字符串,字符串这两个属性属于结构体,数组中就是整数
    // 通过indices获取数组的索引区间
    for i in numbers.indices {
        print("\(i) \(numbers[i])")
    }
    
    let array = [10, 20, 45, 30, 98, 101, 30, 4]
    // 是否包含指定元素或某个条件的元素
    print(array.contains(30))
    print(array.contains(where: {$0 < 3}))
    print(array.contains(where: {$0 <= 4}))
    
    // 所有元素是否符合某个条件
    print(array.allSatisfy({$0 > 10}))
    print(array.allSatisfy({$0 > 3}))
    
    // 查找元素 first last first(where:) last(where:) 返回的都是可选类型
    print(array.first)
    print(array.last)
    print(array.first(where: {$0 > 25}))
    print(array.last(where: {$0 > 30}))
    
    // 查找索引 firstIndex(of:) lastIndex(of:) firstIndex(where:) lastIndex(where:) 返回的都是可选类型
    print(array.firstIndex(of: 9))
    print(array.lastIndex(of: 30))
    print(array.firstIndex(where: {$0 > 26}))
    print(array.lastIndex(where: {$0 > 26}))
     
    // 查找最大最小元素 min() max()
    print(array.min())
    print(array.max())
    
    let errors = [(12, "b"), (23, "a"), (45, "c")]
    print(errors.max(by: { (a , b) -> Bool in
        a.0 < b.0
    }))
    
  3. 添加和删除

    // 末尾添加 append(_:) append(contentsOf:)
    numbers.append(100)
    numbers.append(contentsOf: 200...203)
    
    // 任意位置插入
    numbers.insert(-1, at: 1)
    numbers.insert(contentsOf: 100...104, at: 1)
    
    // 移除单个元素 remove(at:) removeFirst() popLast()
    let removeNum = numbers.remove(at: 1)
    let removeNum = numbers.removeFirst()
    let removeNum = numbers.removeLast()
    // 空数组中使用removeFirst、removeLast会报错 可以使用popLast、
    let removeNum = numbers.popLast()
    
    // 移除多个元素 removeFirst(:) removeLast(:) removeSubrange(_:) removeAll() removeAll(keepingCapacity:)
    numbers.removeFirst(2)
    numbers.removeLast(2)
    numbers.removeSubrange(1...3)
    numbers.removeAll()
    numbers.removeAll(keepingCapacity: true) // 数组容量不会缩小
    
    // 数组切片 arraySlice 类似于String和SubString
    var slice = numbers.dropFirst()
    var slice = numbers.dropFirst(3)
    var slice = numbers.dropLast(3)
    var slice = numbers.drop(while: {$0 < 12})
    var slice = numbers.drop(while: {$0 < 50})
    
    var slice = numbers.prefix(4)
    var slice = numbers.prefix(upTo: 4)
    var slice = numbers.prefix(through: 4)
    var slice = numbers.prefix(while: {$0 < 50})
    
    var slice = numbers.suffix(3)
    var slice = numbers.suffix(from: 5)
    
    var slice = numbers[2...5]
    var slice = numbers[...]
    var slice = numbers[...3]
    var slice = numbers[..<3]
    
    var number2:[Int] = Array(slice)
    
  4. 重排操作

    var array = [Int](1...8)
    // 随即化 shuffle()  shuffled()
    array.shuffle()
    let array2 = array.shuffled()
    
    // 逆序 reverse() reversed()
    array.reverse()
    let array2 = array.reversed()
    
    // 分组
    var numbers = [10, 2, 25, 30, 46, 57, 101, 30, 70]
    let index = numbers.partition(by: {$0 > 30})
    print(index)
    let p1 = numbers[..<index]
    let p2 = numbers[index...]
    
    // 排序 sort() sorted()
    numbers.sort()
    let num2 = numbers.sorted()
    
    // 交换 swapAt(_:_:)
    numbers.swapAt(numbers.startIndex, numbers.endIndex-1)
    
  5. 拼接

    // 字符串数组拼接 joined() joined(separator:)
    let array = ["hello", "world"]
    print(array.joined())
    print(array.joined(separator: ","))
    
    // sequence数组的拼接
    let ranges = [0...3, 5...7, 15...16]
    for range in ranges {
        print(range)
    }
    
    for i in ranges.joined() {
        print(i)
    }
    
    for i in ranges.joined(separator: [-1]) {
        print(i)
    }
    

2.Set

  1. 定义

    Set是指具有某种特定性质的具体或者抽象的对象汇总而成的集体。
    具有确定性、互斥性、无序性
    为了让类型储存在Set中,必须是可哈希的
    
    struct Person {
        var name: String
        var age:Int
    }
    
    extension Person: Hashable {
        func hash(into hasher: inout Hasher) {
            hasher.combine(name)
          	hasher.combine(age)
        }
    }
    
    var personSet = Set<Person>()
    personSet.insert(Person.init(name: "zhangsan", age: 23))
    
  2. 初始化

    // 初始化器
    var letters = Set<Character>()
    letters.insert("c")
    print(letters)
    
    // 数组字面量
    var course: Set<String> = ["Math", "English"]
    let course: Set = ["Math", "English"]
    course.insert("History")
    
  3. 访问、修改

    // 使用for-in遍历,但是set是无序的,如果要顺序遍历,使用sorted()方法
    let courses: Set = ["math", "english", "history"]
    for course in courses {
        print(course)
    }
    
    for course in courses.sorted() {
        print(course)
    }
    
    // 使用count获取个数,isEmpty判断是否为空
    courses.count
    courses.isEmpty
    
    // 添加元素
    // 添加一个元素
    personSet.insert(Person.init(name: "zhangsan", age: 23))
    // 如果已有相等的元素替换,没有则插入
    personSet.update(with: Person.init(name: "lisi", age: 33))
    
    // 如果想判断相等需要实现判断的协议
    extension Person: Equatable {
        static func == (lhs: Person, rhs: Person) -> Bool {
            return lhs.name == rhs.name
        }
    }
    
    var personSet = Set<Person>()
    personSet.insert(Person(name: "zhangsan", age: 23))
    personSet.update(with: Person(name: "lisi", age: 33))
    personSet.update(with: Person(name: "zhangsan", age: 222))
    
    // 移除元素
    // filter(_:)返回符合条件的新set
    let newSet = personSet.filter({$0.age < 100})
    
    personSet.remove(Person(name: "lisi", age: 33))
    personSet.removeAll()
    
    // 移除哈希sort排布后第一个
    personSet.removeFirst()
    
    
  4. 基本Set操作

    // 交集 具有对称性
    set.intersection(set2)
    
    // 并集 具有对称性
    print(set.union(set2))
    
    // 对称差集 具有对称性
    print(set.symmetricDifference(set2))
    
    // 相对补集 不具有对称性
    print(set.subtracting(set2))
    print(set2.subtracting(set))
    
    // 子集 父集
    print(smallSet.isSubset(of: bigSet))
    print(bigSet.isSuperset(of: smallSet))
    
    print(bigSet.isSuperset(of: bigSet))
    
    // 真子集 真父集
    print(smallSet.isStrictSubset(of: bigSet))
    print(bigSet.isStrictSubset(of: bigSet))
    
    // 是否有公共元素 有的话返回false
    print(smallSet.isDisjoint(with: bigSet))
    

Dictionary

  1. 定义

    字典是用来储存无序的互相关联的同一类型的键和同一类型的值的集合
    key必须是可哈希的
    
  2. 初始化

    // 初始器
    let dict1 = Dictionary<String, Int>()
    
    // 简写
    let dic = [String: Int]()
    
    // 字面量
    let dic3: Dictionary<String, Int> = [:]
    let dic = ["zhangsan":23, "lisi":19, "wangwu":30]
    
  3. 遍历、索引

    // 使用count获取个数,isEmpty判断是否为空
    dic.count
    dic.isEmpty
    
    // 遍历
    // for-in
    for (key, value) in dic {
        print("name = \(key), age = \(value)")
    }
    
    // 可通过字典的keys和values来取回可遍历的字典的键或值的集合
    for key in dic.keys {
        print("name = \(key), age = \(dic[key])")
    }
    
    // Dictionary是无序的 可使用sorted()排序
    for key in dic.keys.sorted() {
        print("name = \(key), age = \(dic[key])")
    }
    
  4. 修改

    // 添加/更新
    // 使用下标添加/更新
    personDic["zhaoliu"] = 21
    
    // 使用updateValue:(_:forkey:)添加/更新
    personDic.updateValue(33, forKey: "maliu")
    
    // 移除
    // 使用下标语法给一个键赋值为nil
    personDic["zhaoliu"] = nil
    
    // 使用removeValue(forkey:)
    personDic.removeValue(forKey: "zhaoliu")
    
    // 合并两个字典
    var dict = ["a": 1, "b": 2]
    
    // merging不会改变原字典
    print([dict.merging(["a":2, "c": 5], uniquingKeysWith: { (current, _) in
        current
    })])
    
    print([dict.merging(["a":2, "c": 5], uniquingKeysWith: { (_, new) in
        new
    })])
    // merge 在原字典上修改
    dict.merge(["a":2, "c": 5]) { (current, _) in
        current
    }
    
    // firstIndex
    let index = dict.firstIndex { (_, Value) in
        Value == 1
    }
    print(index)
    var dict = ["a": 1, "b": 2]
    let index = dict.firstIndex { (_, Value) in
        Value == 1
    }
    print(index)
    if let i = index {
        print(dict[i])
    	  print(dict[i].value)
    }
    // 扩容之后index会失效
    
    // 保持固定顺序
    let kvs: KeyValuePairs = ["a":1, "b":2,"c":3]
    print(kvs)
    

posted @ 2022-02-19 10:56  weicy  阅读(37)  评论(0编辑  收藏  举报