SwiftUI RandomAccessCollection 是什么如何用(2020)
得益于Swift的protocol-oriented 設(shè)計(jì)抱环,因此可以非常容易的實(shí)現(xiàn)各種通用算法缎谷。
RandomAccessCollection 介紹
A collection that supports efficient random-access index traversal.
支持高效隨機(jī)訪問的集合
RandomAccess集合可以將索引移動到任意距離烫幕,并可以在O(1)復(fù)雜度時間內(nèi)從了索引之間的距離饭尝。因此隨機(jī)訪問與雙向訪問之間區(qū)別就在于索引移動效率。例如淘这,在O(1)時間內(nèi)就可以額隨機(jī)訪問count屬性袁梗,而不需要迭代整個集合鲁猩。
RandomAccessCollection 位置
實(shí)際應(yīng)用
RandomAccessCollection 可以應(yīng)用在List分頁項(xiàng)目中轰异,我將在后續(xù)教程中進(jìn)行介紹岖沛。
import UIKit
import Foundation
import SwiftUI
extension RandomAccessCollection where Self.Element: Identifiable {
public func isLastItem<Item: Identifiable>(_ item: Item) -> Bool {
guard !isEmpty else {
return false
}
guard let itemIndex = lastIndex(where: { AnyHashable($0.id) == AnyHashable(item.id) }) else {
return false
}
let distance = self.distance(from: itemIndex, to: endIndex)
return distance == 1
}
public func isThresholdItem<Item: Identifiable>(offset: Int,
item: Item) -> Bool {
guard !isEmpty else {
return false
}
guard let itemIndex = lastIndex(where: { AnyHashable($0.id) == AnyHashable(item.id) }) else {
return false
}
let distance = self.distance(from: itemIndex, to: endIndex)
let offset = offset < count ? offset : count - 1
return offset == (distance - 1)
}
}
struct DemoItem: Identifiable {
let id = UUID()
var sIndex = 0
}
let items:[DemoItem] = Array(0...10).map { DemoItem(sIndex: $0) }
items.isLastItem(items[0])
items.isLastItem(items[10])
效果
SwiftUI RandomAccessCollection
參考文獻(xiàn)
更多SwiftUI教程和代碼關(guān)注專欄
- 請關(guān)注我的專欄 SwiftUI教程與源碼