- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
使用 _base
属性访问 ReverseRandomAccessCollection
的元素是一种好习惯吗?
let myArray = [1, 2, 3]
print(myArray.first) // returns 1
print(myArray.reversed().first) // returns 3
print(myArray.reversed()._base.first) // return 1, which is the underlying base array
最佳答案
ReverseRandomAccessCollection
(您可以看到 its full implementation here)是一个简单的包装器,它向底层 RandomAccessCollection
(这节省了 O(n) 遍历它的时间。
实现这一点的方法是通过保留底层集合的 _base
属性,然后实现 RandomAccessCollection
协议(protocol)以呈现它的反向 View ,例如反向索引遍历(评论我的):
public struct ReversedRandomAccessCollection<
Base : RandomAccessCollection
> : RandomAccessCollection {
public let _base: Base // the underlying collection to present the reversed view on
// ...
public var startIndex: Index { // startIndex accesses endIndex of _base
return ReversedRandomAccessIndex(_base.endIndex)
}
public var endIndex: Index { // endIndex accesses startIndex of _base
return ReversedRandomAccessIndex(_base.startIndex)
}
public func index(after i: Index) -> Index { // index(after:) gets the index(before:)
return ReversedRandomAccessIndex(_base.index(before: i.base))
}
public func index(before i: Index) -> Index { // index(before:) gets the index(after:)
return ReversedRandomAccessIndex(_base.index(after: i.base))
}
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
// index offset is simply made negative,
// then forwarded to base's index(_:offsetBy:) method
return ReversedRandomAccessIndex(_base.index(i.base, offsetBy: -n))
}
// ...
}
因为 _base
属性是 public
,所以没有什么可以阻止您使用它。但是,带下划线前缀的属性和方法用于指示不属于公共(public) API 的实现细节——因为它们通常不是设计为直接使用的,并且可能会在没有警告的情况下更改。
在这种情况下,您可以在调用 reversed()
之前简单地处理数组——它将与 _base
相同(直到您改变它)。因此,不要这样做:
myArray.reversed()._base.first
你应该这样做:
myArray.first
这将产生相同的结果。
关于arrays - Reverse RandomAccessCollection 的 `_base` 属性是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39547399/
我通常实现行为类似于数组的类型,例如: struct Dataset: RandomAccessCollection { let ids: [Int] // Other propert
我有一个协议(protocol),我想表达一个函数/变量可以返回一个特定类型的 RandomAccessCollection - 不一定是一个 Array 因为对于一个实现它使用访问数据的库。将库调用
根据 Swift 5 文档,String 的方法 randomElement() 复杂度为 O(1) 或 O(*n*) 取决于符合 RandomAccessCollection 协议(protocol
当我们尝试从 Array 中检索一系列元素时,我们会返回一个 ArraySlice: let array = [1, 3, 5, 2] let arraySlice = array[..(_ c: T
使用 _base 属性访问 ReverseRandomAccessCollection 的元素是一种好习惯吗? let myArray = [1, 2, 3] print(myArray.first)
我是一名优秀的程序员,十分优秀!