将元素添加到 Swift 中的数组 [英] Add an element to an array in Swift

查看:33
本文介绍了将元素添加到 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:

[史蒂夫"、比尔"、莱纳斯"、布雷特"、蒂姆"]

我应该使用什么方法?

如果我想在数组的前面添加一个元素呢?是否有一个恒定的时间unshift?

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 中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆