ios 将元素添加到 Swift 中的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24002733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:15:37  来源:igfitidea点击:

Add an element to an array in Swift

iosarraysswift

提问by Fela Winkelmolen

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"]

["Steve", "Bill", "Linus", "Bret", "Tim"]

What method should I use?

我应该使用什么方法?

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

那么我想在数组前面添加一个元素的情况呢?是否有一个恒定的时间不变?

回答by Mick MacCallum

As of Swift 3 / 4 / 5, this is done as follows.

Swift 3 / 4 / 5 开始,这是按如下方式完成的。

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.

将不同 Array 的内容插入到您的 Array 中。

anArray.insert(contentsOf: ["Moar", "Strings"], at: 0)

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

更多信息可以在“ The Swift Programming Language”的“Collection Types”一章中找到,从第 110 页开始。

回答by steveq88

You can also pass in a variable and/or object if you wanted to.

如果需要,您还可以传入变量和/或对象。

var str1:String = "John"
var str2:String = "Bob"

var myArray = ["Steve", "Bill", "Linus", "Bret"]

//add to the end of the array with append
myArray.append(str1)
myArray.append(str2)

To add them to the front:

要将它们添加到前面:

//use 'insert' instead of append
myArray.insert(str1, atIndex:0)
myArray.insert(str2, atIndex:0)

//Swift 3
myArray.insert(str1, at: 0)
myArray.insert(str2, at: 0)

As others have already stated, you can no longer use '+=' as of xCode 6.1

正如其他人已经说过的,从 xCode 6.1 开始,您不能再使用 '+='

回答by rickster

To add to the end, use the +=operator:

要添加到末尾,请使用+=运算符:

myArray += ["Craig"]
myArray += ["Jony", "Eddy"]

That operator is generally equivalent to the append(contentsOf:)method. (And in really old Swift versions, could append single elements, not just other collections of the same element type.)

该运算符通常等效于该append(contentsOf:)方法。(并且在非常旧的 Swift 版本中,可以附加单个元素,而不仅仅是相同元素类型的其他集合。)

There's also insert(_:at:)for inserting at any index.

还有insert(_:at:)用于在任何索引处插入。

If, say, you'd like a convenience function for inserting at the beginning, you could add it to the Arrayclass with an extension.

比如说,如果你想要一个方便的函数来在开头插入,你可以将它添加到Array带有扩展名的类中。

回答by Aqib Mumtaz

Use += and + operators :

使用 += 和 + 运算符:

extension Array {

}

func += <V> (inout left: [V], right: V) {
    left.append(right)
}

func + <V>(left: Array<V>, right: V) -> Array<V>
{
    var map = Array<V>()
    for (v) in left {
        map.append(v)
    }

    map.append(right)

    return map
}

then use :

然后使用:

var list = [AnyObject]()
list += "hello" 
list += ["hello", "world!"]
var list2 = list + "anything"

回答by Sebastian Ustinelli

Here is a small extension if you wish to insert at the beginning of the array without loosing the item at the first position

如果您希望在数组的开头插入而不丢失第一个位置的项目,这是一个小的扩展

extension Array{
    mutating func appendAtBeginning(newItem : Element){
        let copy = self
        self = []
        self.append(newItem)
        self.appendContentsOf(copy)
    }
}

回答by iOS

In Swift 4.1 and Xcode 9.4.1

在 Swift 4.1 和 Xcode 9.4.1 中

We can add objects to Array basically in Two ways

我们基本上可以通过两种方式向 Array 添加对象

let stringOne = "One"
let strigTwo = "Two"
let stringThree = "Three"
var array:[String] = []//If your array is string type

Type 1)

类型 1)

//To append elements at the end
array.append(stringOne)
array.append(stringThree)

Type 2)

类型 2)

//To add elements at specific index
array.insert(strigTwo, at: 1)

If you want to add two arrays

如果要添加两个数组

var array1 = [1,2,3,4,5]
let array2 = [6,7,8,9]

let array3 = array1+array2
print(array3)
array1.append(contentsOf: array2)
print(array1)

回答by aglasser

From page 143 of The Swift Programming Language:

来自 The Swift Programming Language 的第 143 页:

You can add a new item to the end of an array by calling the array's append method

Alternatively, add a new item to the end of an array with the addition assignment operator (+=)

您可以通过调用数组的 append 方法将新项添加到数组的末尾

或者,使用加法赋值运算符 (+=) 在数组末尾添加一个新项

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l

摘自:Apple Inc. “The Swift Programming Language”。电子书。https://itun.es/us/jEUH0.l

回答by Benjohn

To add to the solutions suggesting append, it's useful to know that this is an amortised constant timeoperation in many cases:

要添加到建议append解决方案中,知道在许多情况下这是一个摊销的恒定时间操作是有用的:

Complexity: Amortized O(1) unless self's storage is shared with another live array; O(count) if self does not wrap a bridged NSArray; otherwise the efficiency is unspecified.

复杂性:摊销 O(1),除非 self 的存储与另一个实时阵列共享;O(count) 如果 self 没有包装桥接的 NSArray;否则效率是不确定的。

I'm looking for a conslike operator for Swift. It should return a newimmutable array with the element tacked on the end, in constant time, without changing the original array. I've not yet found a standard function that does this. I'll try to remember to report back if I find one!

我正在cons为 Swift寻找类似的运算符。它应该在恒定时间内返回一个新的不可变数组,该数组的末尾添加了元素,而不会更改原始数组。我还没有找到执行此操作的标准函数。如果我找到了,我会尽量记得回来报告!

回答by Tikhonov Alexander

If you want to append unique object, you can expand Arraystruct

如果要追加唯一对象,可以展开Arraystruct

extension Array where Element: Equatable {
    mutating func appendUniqueObject(object: Generator.Element) {
        if contains(object) == false {
            append(object)
        }
    }
}

回答by ANIL.MUNDURU

You could use

你可以用

Myarray.insert("Data #\(index)", atIndex: index)