229_using_collections_effectivel

2019-11-18  本文已影响0人  三三At你

0x0 protocol Collection

protocol Collection : Sequence {
    associatedtype Element
    associatedtype Index : Comparable
    //[x]取值语法糖
    subscript(position: Index) -> Element { get }
    //开始下标
    var startIndex: Index { get }
    //结束下标
    var endIndex: Index { get }
    //根据下标获取元素
    func index(after i: Index) -> Index 
}   
//当前下标前一个下标
func index(before: Self.Index) -> Self.Index
//当前下标后一个下标
func index(after: Self.Index) -> Self.Index
// constant time
//下标偏移
func index(_ idx: Index, offsetBy n: Int) -> Index 
//两个下标的间距
func distance(from start: Index, to end: Index) -> Int

0x2 索引

//推荐使用
array.first 
set.first
extension Collection { 
    var second: Element? {
        // Is the collection empty?
        guard self.startIndex != self.endIndex else { return nil } 
        // Get the second index
        let index = self.index(after: self.startIndex)
        // Is that index valid?
        guard index != self.endIndex else { return nil } 
        // Return the second element
        return self[index]
    } 
}
extension Collection { 
    var second: Element? {
        return self.dropFirst().first
    }
}
// Slicing Keeps Underlying Storage
extension Array {
    var firstHalf: ArraySlice<Element> {
        return self.dropLast(self.count / 2)
    } 
}
var array = [1, 2, 3, 4, 5, 6, 7, 8]
var firstHalf = array.firstHalf // [1, 2, 3, 4]
array = [] //释放集合
print(firstHalf.first!)// 1
 
let copy = Array(firstHalf) // [1, 2, 3, 4] 拷贝切片以便后续使用
firstHalf = [] //释放切片 保证集合可以释放
print(copy.first!)// 1

0x3 lazy函数

let items = (1...4000).map { $0 * 2 }.filter { $0 < 10 } //立刻计算出值
let items = (1...4000).lazy.map { $0 * 2 }.filter { $0 < 10 } //用到的时候在去计算,每次都会重新计算
let bears = ["Grizzly", "Panda", "Spectacled", "Gummy Bears", "Chicago"]
 
let redundantBears = bears.lazy.filter {
print("Checking '\($0)'")
}
return $0.contains("Bear")
 
let filteredBears = Array(redundantBears) // ["Gummy Bears"] //缓存结果
print(filteredBears.first!) // Gummy Bears

0x4 可变集合与可区间替换集合

// constant time
subscript(_: Self.Index) -> Element { get set }
replaceSubrange(_:, with:)

0x5 为什么集合操作会crash

0x6 多线程

swift集合都是对单线程进行优化的
使用ThreadSanitizer 来检测资源竞争


image.png

0x7 Foundation 集合

上一篇下一篇

猜你喜欢

热点阅读