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?
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.
Swift Array append() The append() method adds a new element at the end of the array.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With