419

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

What method should I use?

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

Naresh
  • 16,698
  • 6
  • 112
  • 113
Fela
  • 26,730
  • 8
  • 26
  • 24
  • 133
    Steve Jobs, Bill Gates, Linus Torvalds, but who is Bret? - I feel like I should know (and I'm probably going to kick myself when I find out!) – Jimmery Mar 17 '15 at 16:54
  • 33
    Bret Victor? http://worrydream.com – onekiloparsec Apr 05 '15 at 13:26
  • 26
    Bret Victor is correct. His work is said to have been an inspiration for parts of swift – Fela Apr 05 '15 at 17:14
  • 3
    bare in mind you can never use [*subscript*](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Subscripts.html) to add an element into a *new* index. subscripting is only used for updating a value or reading from an *existing* index. So if you have `let array = [Int]()` you can never say `array[0] = 42` It will give **index out of range** error. You should use `array.append(42)`. Why can't you subscript? For the same reason you can't do `letters[3] = d` for `let letters = [a,b,c]`. The 3rd index is non-existent as is array[0] before a value! – mfaani Nov 26 '16 at 13:29
  • 9
    Don't teach him how to do this. Tim should not be allowed in this array, its an insult to the others.... – Otziii Nov 01 '17 at 15:13
  • 3
    @Otziii not at all if "Tim" refers to [this person](https://en.wikipedia.org/wiki/Tim_Berners-Lee) instead of [this person](https://en.wikipedia.org/wiki/Tim_Cook) – ggorlen Oct 26 '21 at 22:07

15 Answers15

725

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)

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

Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
  • 2
    Great answer. The inconsistency in the way Apple implemented this is kind of irritating. Presumably, **anArray+="Foo"** does the same thing as **anArray+=["Foo"]** Personally, I'll only be using the latter syntax to avoid confusing myself. – original_username Jul 07 '14 at 05:56
  • 13
    anArray+="Foo" does not work anymore from xCode 6 beta 5 – Amitay Aug 07 '14 at 06:44
  • Can you do a list the method's and functions for create and fill a array too?? :D –  Dec 12 '14 at 18:40
  • Is there any reason why `.insert` would fail but `.append` would be successful? I'm having that problem with an array right now but can't seem to find anything online regarding it. I could understand both failing if the array were immutable. – MusiGenesis Aug 12 '15 at 21:07
  • @MusiGenesis Is it failing at compile time or at run time? The first thing that comes to mind on why insert might fail while append succeeds would be an index out of bounds run time error. Can you provide some context around your problem? – Mick MacCallum Aug 12 '15 at 21:15
  • 1
    It's failing at run time. There are elements already in the array that I'm attempting to insert, so that's not it. My workaround is to create a new array with the element that I'm attempting to insert, and then append all the elements from the original array. Pretty sure this is the result of a retain problem elsewhere - somehow these objects are fine so long as they're left in their original array spots, but if iOS attempts to move them (as a result of the insert) there's a crash. Or else this is some weird Swift/IB problem. – MusiGenesis Aug 14 '15 at 13:24
  • 1
    `splice` rename to `insertContentsOf` in Swift 2. – Almas Sapargali Nov 14 '15 at 04:16
25

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

Swift Hipster
  • 1,604
  • 3
  • 16
  • 24
Steve Quatrale
  • 360
  • 3
  • 4
21

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.)

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

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

rickster
  • 124,678
  • 26
  • 272
  • 326
  • If `myArray` is of type `Array`, then the first line is incorrect. The `+=` operator can only be used if both `myArray` and the right operand are of type `Array`. – Bart Jacobs Jan 26 '15 at 15:08
  • 1
    It was correct back when I posted this answer, but the language has changed since. Answer updated. – rickster Jan 26 '15 at 15:33
  • Saying that `+=` and `append` are equivalent is not correct, the former involves the creation of a temporary array that will be discarded as soon as the operator function consumes it. – Cristik Feb 25 '19 at 22:04
13

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"
Aqib Mumtaz
  • 4,936
  • 1
  • 36
  • 33
  • In the second function, there is no need to iterate over the left array. Doing `var copy = left` and then appending `copy.append(right)` is enough. In Swift, arrays are value types, not reference types. – Natan R. May 28 '20 at 12:59
  • You might want too add `extension Array where Element == YourClass {` if it is not compiling – itMaxence Oct 21 '21 at 16:31
6

Use Deque instead of Array

The main benefit of Deque over Array is that it supports efficient insertions and removals at both ends.

https://swift.org/blog/swift-collections/


var names:Deque = ["Steve", "Bill", "Linus", "Bret"]


Add 'Tim' at the end of names

names.append("Tim")

Add 'Tim' at the begining of names

names.prepend("John")

Remove the first element of names

names.popFirst() // "John"

Remove the last element of names

names.popLast() // "Tim"
mahan
  • 12,366
  • 5
  • 48
  • 83
5

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)
    }
}
5

In Swift 4.1 and Xcode 9.4.1

We can add objects to Array basically in Two ways

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

Type 1)

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

Type 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)
Naresh
  • 16,698
  • 6
  • 112
  • 113
2

From page 143 of The Swift Programming Language:

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 (+=)

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

Community
  • 1
  • 1
aglasser
  • 3,059
  • 3
  • 13
  • 10
2

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

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.

I'm looking for a cons like operator for Swift. It should return a new immutable 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!

Community
  • 1
  • 1
Benjohn
  • 13,228
  • 9
  • 65
  • 127
1

You could use

Myarray.insert("Data #\(index)", atIndex: index)
Jojodmo
  • 23,357
  • 13
  • 65
  • 107
ANIL.MUNDURU
  • 403
  • 4
  • 2
1

If you want to append unique object, you can expand Array struct

extension Array where Element: Equatable {
    mutating func appendUniqueObject(object: Generator.Element) {
        if contains(object) == false {
            append(object)
        }
    }
}
Tikhonov Aleksandr
  • 13,945
  • 6
  • 39
  • 53
1

If the array is NSArray you can use the adding function to add any object at the end of the array, like this:

Swift 4.2

var myArray: NSArray = []
let firstElement: String = "First element"
let secondElement: String = "Second element"

// Process to add the elements to the array
myArray.adding(firstElement)
myArray.adding(secondElement)

Result:

print(myArray) 
// ["First element", "Second element"]

That is a very simple way, regards!

Radames E. Hernandez
  • 4,235
  • 27
  • 37
1

In Swift 4.2: You can use

myArray.append("Tim") //To add "Tim" into array

or

myArray.insert("Tim", at: 0) //Change 0 with specific location 
Ridho Octanio
  • 543
  • 5
  • 14
1

Example: students = ["Ben" , "Ivy" , "Jordell"]

1) To add single elements to the end of an array, use the append(_:)

students.append(\ "Maxime" )

2) Add multiple elements at the same time by passing another array or a sequence of any kind to the append(contentsOf:) method

students.append(contentsOf: ["Shakia" , "William"])

3) To add new elements in the middle of an array by using the insert(_:at:) method for single elements

students.insert("Liam" , at:2 )

4) Using insert(contentsOf:at:) to insert multiple elements from another collection or array literal

students.insert(['Tim','TIM' at: 2 )

Ronak Patel
  • 609
  • 4
  • 16
0

Swift 5.3, I believe.

The normal array wasvar myArray = ["Steve", "Bill", "Linus", "Bret"] and you want to add "Tim" to the array, then you can use myArray.insert("Tim", at=*index*)so if you want to add it at the back of the array, then you can use myArray.append("Tim", at: 3)