Swift 集合类型全解析
1. 数组操作
1.1 移除数组元素
在 Swift 中,有多种方法可以从数组中移除元素。
- 使用 remove(at:) 方法移除指定索引的元素:
let oldArrayValue = shoppingList.remove(at: 1)
oldArrayValue
shoppingList
上述代码移除了 shoppingList 数组中索引为 1 的元素 “Chicken”,移除的元素被存储在 oldArrayValue 中。
- 若不需要保留移除的值,也可直接使用 remove(at:) :
shoppingList.remove(at: 3)
shoppingList
此代码移除了索引为 3 的元素 “Fish”。
- 若要移除数组的最后一个元素,可使用 removeLast() 方法,还可选择将移除的值赋给常量或变量:
let lastItem = shoppingList.removeLast()
1.2 遍历数组
可以使用 for-in 循环遍历数组中的每个元素:
超级会员免费看
订阅专栏 解锁全文
62

被折叠的 条评论
为什么被折叠?



