Add an element to an array in Swift(在 Swift 中将元素添加到数组中)
问题描述
假设我有一个数组,例如:
Suppose I have an array, for example:
var myArray = ["Steve", "Bill", "Linus", "Bret"]
稍后我想将一个元素推送/附加到所述数组的末尾,以获取:
And later I want to push/append an element to the end of said array, to get:
[Steve"、Bill"、Linus"、Bret"、Tim"]
我应该使用什么方法?
如果我想在数组的front中添加一个元素呢?是否有恒定的时间不移位?
And what about the case where I want to add an element to the front of the array? Is there a constant time unshift?
推荐答案
从 Swift 3/4/5 开始,如下所示.
As of Swift 3 / 4 / 5, this is done as follows.
将新元素添加到数组的末尾.
To add a new element to the end of an Array.
anArray.append("This String")
将不同的数组附加到数组的末尾.
To append a different Array to the end of your Array.
anArray += ["Moar", "Strings"]
anArray.append(contentsOf: ["Moar", "Strings"])
在你的数组中插入一个新元素.
To insert a new element into your Array.
anArray.insert("This String", at: 0)
将不同数组的内容插入到您的数组中.
To insert the contents of a different Array into your Array.
anArray.insert(contentsOf: ["Moar", "Strings"], at: 0)
更多信息可以在Swift 编程语言",从第 110 页开始.
More information can be found in the "Collection Types" chapter of "The Swift Programming Language", starting on page 110.
这篇关于在 Swift 中将元素添加到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Swift 中将元素添加到数组中
基础教程推荐
- 如何从 logcat 中删除旧数据? 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
