gpt4 book ai didi

arrays - Reverse RandomAccessCollection 的 `_base` 属性是什么?

转载 作者:搜寻专家 更新时间:2023-10-31 22:44:56 26 4
gpt4 key购买 nike

使用 _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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com