【问题标题】:Array<T> or Slice<T> struct type understanding structureArray<T> 或 Slice<T> struct 类型理解结构
【发布时间】:2014-09-26 05:32:12
【问题描述】:

虽然 Array struct def 是:

struct Array<T> : MutableCollection, Sliceable {
    typealias Element = T
    var startIndex: Int { get }
    var endIndex: Int { get }
    subscript (index: Int) -> T
    func generate() -> IndexingGenerator<[T]>
    typealias SliceType = Slice<T>
    subscript (subRange: Range<Int>) -> Slice<T>
}

而 MutableCollection 是:

protocol MutableCollection : Collection {
    subscript (i: Self.IndexType) -> Self.GeneratorType.Element { get set }
}

然后收藏:

protocol Collection : Sequence {
    subscript (i: Self.IndexType) -> Self.GeneratorType.Element { get }
}

然后是序列:

protocol Sequence {
    typealias GeneratorType : Generator
    func generate() -> GeneratorType
}

和可切片:

protocol Sliceable {
    typealias SliceType
    subscript (_: Range<Self.IndexType>) -> SliceType { get }
}

(Slice几乎相当于Array)

后台在哪里?

【问题讨论】:

标签: swift swiftype


【解决方案1】:

这是私人的。它曾经被公开为ArrayBuffer,但他们从公共标题中删除了它(我相信在 beta 4 中)。他们仍然(间接地)公开了 beta 4 中 _ContiguousArrayBuffer 的存在。

自然的问题是“你为什么想知道?”存储细节不是Array 接口的一部分,因此它们可能会发生变化。请记住,Array 独立于 ContiguousArray,因此几乎任何您认为想要对后备存储执行的操作都可能不安全(因为它甚至没有被承诺是连续的)。

所有那些花哨的东西,实际上你确实可以访问承诺看起来像后备商店的东西。那是withUnsafePointerToElements。这将为您提供一个指针,您可以在该指针上进行指针数学运算并获取数组中的元素(就像在 C 中一样)。 (此方法在标头中,但不在文档中,因此它可能无法在 beta 中存活。)

您还可以将&amp;arrayT 传递给一个接受*T 的C 函数,这将使它看起来那里确实有一个连续的内存块。这是在文档中,所以它更有可能保持真实。

【讨论】:

  • 感谢 Rob 的回复和建议。
猜你喜欢
  • 1970-01-01
  • 2022-11-14
  • 1970-01-01
  • 2015-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-27
相关资源
最近更新 更多