gpt4 book ai didi

arrays - Swift 中的 Array、ContiguousArray 和 ArraySlice 之间有什么区别?

转载 作者:IT王子 更新时间:2023-10-29 05:13:24 24 4
gpt4 key购买 nike

在 Swift 2 中,三种数组变体之间的主要区别是什么:

  • 数组
  • 连续数组
  • 数组切片

谁能用真实世界的例子解释一下?

最佳答案

来自docs :

连续数组:

Efficiency is equivalent to that of Array, unless T is a class or @objc protocol type, in which case using ContiguousArray may be more efficient. Note, however, that ContiguousArray does not bridge to Objective-C. See Array, with which ContiguousArray shares most properties, for more detail.

基本上,无论何时在数组中存储@objc 协议(protocol) 类型,您都可能需要考虑使用ContiguousArray 而不是数组

数组切片

ArraySlice always uses contiguous storage and does not bridge to Objective-C.

Warning: Long-term storage of ArraySlice instances is discouraged

Because a ArraySlice presents a view onto the storage of some larger array even after the original array's lifetime ends, storing the slice may prolong the lifetime of elements that are no longer accessible, which can manifest as apparent memory and object leakage. To prevent this effect, use ArraySlice only for transient computation.

当您想从数组中获取子范围时,大多数时候都会使用 ArraySlices,例如:

let numbers = [1, 2, 3, 4]
let slice = numbers[Range<Int>(start: 0, end: 2)] //[1, 2]

任何其他情况你应该使用Array

关于arrays - Swift 中的 Array<T>、ContiguousArray<T> 和 ArraySlice<T> 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31290576/

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