SwiftUI RandomAccessCollection 是什么如何用(2020)
得益于Swift的protocol-oriented 设计,因此可以非常容易的实现各种通用算法。
RandomAccessCollection 介绍
A collection that supports efficient random-access index traversal.
支持高效随机访问的集合
RandomAccess集合可以将索引移动到任意距离,并可以在O(1)复杂度时间内从了索引之间的距离。因此随机访问与双向访问之间区别就在于索引移动效率。例如,在O(1)时间内就可以额随机访问count属性,而不需要迭代整个集合。
实际应用
RandomAccessCollection 可以应用在List分页项目中,我将在后续教程中进行介绍。
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教程和代码关注专栏
- 请关注我的专栏 SwiftUI教程与源码