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

查看:67
本文介绍了在 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 中将元素添加到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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