swift - Swift 中的容量数组

标签 swift

如何在没有 RepeatedValues 的情况下初始化具有最大容量的数组?

var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5)

就像这个例子中的 repeatedValue。我们可以在没有值的情况下进行初始化吗?

最佳答案

在 Xcode 中通过 CMD 单击 Array 类型可以找到以下函数定义(以及文档注释):

/// Ensure the array has enough mutable contiguous storage to store
/// minimumCapacity elements in.  Note: does not affect count.
/// Complexity: O(N)
mutating func reserveCapacity(minimumCapacity: Int)

所以在某种程度上,您可以告诉数组为给定的容量预先分配存储空间,方法如下:

var results: [T] = []
results.reserveCapacity(100)

理论上,一百 append阵列上的 s 应该比没有容量预留调用时表现更好。


不过,要强制执行“最大”容量,除了手动放置自定义代码外,没有其他方法可以做到这一点 nil s 到 Optional<T> 的数组中s 上限为@Bryan 在问题评论中建议的最大大小。

关于swift - Swift 中的容量数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24427905/

相关文章:

iOS-swift 导航 Controller 样式不正确

ios - 在 Swift 中以编程方式制作 Segue

ios - 同时从 TableView 行和核心数据中删除项目

android - 相当于 Swift “extensions” 的 Dart 是什么?

ios - 如何从 SKScene 到 UIViewController?

ios - "SCNAudioSource *_steps[StepsSoundCount][AAPLFloorMaterialCount]"的类型

ios - Swift:从另一个 View Controller 调用函数使对象为零

ios - UISearchController 需要额外点击才能成为第一响应者

iOS 11 UIStackView 填充按比例分布导致奇怪的 View 加载动画

ios - 单个 UIViewController 中的多个 Collection View 未调用 cellForItemAtIndexPath indexPath