一个元素添加到斯威夫特数组 [英] Add an element to an array in Swift

查看:116
本文介绍了一个元素添加到斯威夫特数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组,例如:

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:

[史蒂夫,条例,莱纳斯,布雷,添]

我应该使用什么方法?

和在哪里我想一个元素添加到阵列中的的情况是什么?是否有一个恒定的时间不印字?

And what about the case where I want to add an element to the front of the array? Is there a constant time unshift?

推荐答案

您有几个选项用于附加元素的数组。在早期测试版,您可以使用+ =运算符追加一个单独的元素,但这已不再是这种情况。然而,你仍然可以使用附加功能。

You had a couple of options for appending an element to an array. In early betas, you could use the += operator to append an individual element, but this is no longer the case. You can however still use the append function.

anArray.append("This String")

如果您想从不同阵列多个元素追加到您的阵列,您仍然可以使用+ =运算符或扩展方法。

If you're looking to append more elements from a different array to your array, you can still use the += operator, or the extend method.

anArray += ["Moar", "Strings"]
anArray.extend(["Moar", "Strings"])

要在数组开头插入一个对象,你可以使用插入方法。

To insert a single object at the beginning of the array, you can use the insert method.

anArray.insert("This String", atIndex: 0)

要在一个数组的开头插入一个不同的数组的内容,你可以用拼接的方法。

To insert the contents of a different array at the beginning of an array, you can use the splice method.

anArray.insertContentsOf(["So", "Many", "Strings"], at: 0)

在插入件和insertContentsOf的情况下,秒参数可以是在接收阵列的任何有效的索引

In the case of insert and insertContentsOf, the seconds argument can be any valid index of the receiving array.

更多信息可以在集合类型中找到的一章斯威夫特编程语言,从110页。

More information can be found in the "Collection Types" chapter of "The Swift Programming Language", starting on page 110.

这篇关于一个元素添加到斯威夫特数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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