You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中数组容量的扩容机制具体是怎样的?

Swift数组扩容机制的测试与观察

我之前在Apple官方文档中看到这样的说明:

When you add elements to an array and that array begins to exceed its reserved capacity, the array allocates a larger region of memory and copies its elements into the new storage. The new storage is a multiple of the old storage’s size.

为了实际验证这个扩容逻辑,我在Playground里创建了几个测试示例。第一个示例的结果看起来完全符合文档的描述:

var array = [1, 2, 3, 4, 5]
array.capacity // 输出:5
array.append(contentsOf: [6, 7, 8, 9, 10])
array.capacity // 输出:10
array.append(11)
array.capacity // 输出:20

但是……

内容的提问来源于stack exchange,提问作者Roberto Sampaio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:33:02