Collection

作者: 小万叔叔 | 来源:发表于2017-03-14 16:42 被阅读12次

ArraySlice 的内存结构

//ArraySlice 的内存结构 实际只是包含了一个ptr 和 一个指向开始和结束位置的索引
//因此 ArraySlice 的执行效率会更高
// +---------+---+
// | length  | 5 |
// +---------+---+
// | storage ptr |
// +---------+---+
//           |
//           v
//           +---+---+---+---+---+---------------------+
//           | 1 | 2 | 3 | 4 | 5 |  reserved capacity  |
//           +---+---+---+---+---+---------------------+
//           ^
//           |
// +---------+---+
// | storage ptr |
// +---------+---+
// | beg idx | 0 |
// +---------+---+
// | end idx | 3 |  ArraySlice for [0...2]
// +---------+---+

基本操作

//Set
    var setA: Set = [1, 2, 3, 4, 5, 6]
    var setB: Set = [4, 5, 6, 7, 8, 9]

//base
    setA.isEmpty
    setA.contains(3)
    setA.remove(at: setA.startIndex)
    setA.insert(8)
    print(setA)
//    setA.removeAll()
    for c in setA {
        print(c)
    }
    setA.forEach {
        print($0)
    }
    print(setA.sorted())

//返回新对象版本
    let unionSet = setA.union(setB)
    let subtractionSet = setA.subtracting(setB)
    let symmetricSet = setA.symmetricDifference(setB)
    let intersectionSet = setA.intersection(setB)

    print("\(unionSet)-\(subtractionSet)-\(symmetricSet)-\(intersectionSet)")

//Mutating 版本, 都加上form
    setA.formUnion(setB)
    print("\(setA)")
    setA.formIntersection(setB)
    print("\(setA)")
    setA.formSymmetricDifference(setB)
    print("\(setA)")

    //IndexSet CharacterSet
    let c: Set<Int> = [1, 2, 3, 3, 6]
    print(c)
    let charSet = Set<Character>(arrayLiteral: "1", "2")
    print(charSet)

    //Dictionary
    //1. 一般不要用class 作为 key,因为 Class 可能会发生改变,如果 Class 改变后他的 Hash 也要跟着变,
    //这样就无法根据Hash表来找到正确的元素了。
    let dic: [String: Any] = ["key1": 1, "key": 2]
    //dic 的map 默认行为是返回一个 map
    print(dic.map {
        $1
    })

    //函数对序列的影响
    var currentMap = [1, 2, 3, 4, 5]
    print(currentMap.map {
        $0 * $0
    })
    print(currentMap.max())
    print(currentMap.min())
    //注意分区是在当前的结构上操作,
    do {
        let pivot = try currentMap.partition(by: {
            $0 > 2
        })
        print(pivot)
    }catch {
    }

设计一个去重的Array函数

//让序列支持去重
extension Sequence where Iterator.Element: Hashable {
    //定义一个函数用来做去重
    //O(n) 时间复杂度
    func flite() -> [Iterator.Element] {
        var tempSet: Set<Iterator.Element> = Set<Iterator.Element>()
        //用到了序列自身的 filter 方法,用一个临时的 set 来判断是否已经被包含
        return filter {
            if tempSet.contains($0) {
                return false
            } else {
                tempSet.insert($0)
                return true
            }
        }
    }
}

检查CopyOnWrite

   let pointArray = [1, 2, 3, 4, 5]
    //获取地址,来检查copyOnWrite
    func getBufferAddress<T>(of array: [T]) -> String {
        return array.withUnsafeBufferPointer { buffer in
            return String(describing: buffer.baseAddress)
        }
    }
    let first = [1, 2, 3, 4]
    var second = first
    print(getBufferAddress(of: first))
    print(getBufferAddress(of: second))
    second.append(5)
    print(getBufferAddress(of: second))
     //OutPut
    Optional(0x00007fbce9403370)
    Optional(0x00007fbce9403370)
    Optional(0x00007fbce9405dd0)

高阶函数

    //高阶函数
    //filter, map , reduce, flatmap
    //Filter
    let myArray: [Int] = [3, 5, 8, 10, 12, 14]
    myArray.filter {
        $0 % 2 != 0
    }
    let filterArray = myArray.myFilter {
        $0 % 2 != 0
    }
    print(filterArray)

    //Reduce
    let myArray1: [String] = ["a", "b", "c", "d", "e"]
    var reduceStr = myArray1.reduce("", +)
    //注意+也满足传入两个参数,输入一个相同类型的值
    reduceStr = myArray1.myReduce(result: "", +)
    print(reduceStr)


    //FlatMap
    //FlatMap 接收一个成员,返回一个类型, 然后在把结果组合成一个数组
    let dic1: [String: Int] = ["a": 1, "b": 2, "c": 3]
    let str = dic1.flatMap { element -> String? in
        var v: String = String(element.value)
        return v
    }

    let map = dic1.flatMap { animal in
        return dic.map { id in
            (animal, id)
        }
    }

    let flatMap = dic1.myFlatMap { element -> (String, Int) in
        return (element.0, element.1)
    }
    print(flatMap)

//实现基本的高阶函数Filter
extension Array {
    func myFilter(_ trans: (Element) -> Bool) -> [Element] {
        var filterArray: [Element] = []
        for element in self where trans(element) {
            filterArray.append(element)
        }
        return filterArray
    }

    func myReduce<T>(result: T, _ trans: (T, Element) -> T) -> T {
        var reduce = result
        for element in self {
            reduce = trans(reduce, element)  //如果传入 + ,则这里相当于 reduce + element
        }
        return reduce
    }
}

extension Dictionary {
    //Element 代表迭代的成员类型,大写的Key, Value 代表key和value 的类型
    func myFlatMap<T>(transform: (Element) -> T) -> [T] {
        var tmp: [T] = []
        for v in self {
            let ret = transform(v)
            tmp.append(ret)
        }
        return tmp
    }
}

相关文章

网友评论

    本文标题:Collection

    本文链接:https://www.haomeiwen.com/subject/jpshnttx.html