Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an element to an array in 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"]

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?

like image 772
Fela Avatar asked Jun 02 '14 20:06

Fela


People also ask

Can you append an array to an array Swift?

To append another Array to this Array in Swift, call append(contentsOf:) method on this array, and pass the other array for contentsOf parameter. append(contentsOf:) method appends the given array to the end of this array.

What is append in Swift?

Swift Array append() The append() method adds a new element at the end of the array.

How do I change the value of an array in Swift?

To replace an element with another value in Swift Array, get the index of the match of the required element to replace, and assign new value to the array using the subscript.


2 Answers

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.

like image 131
Mick MacCallum Avatar answered Sep 22 '22 17:09

Mick MacCallum


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

like image 32
Steve Quatrale Avatar answered Sep 23 '22 17:09

Steve Quatrale