Add an element to an array in Swift
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 appendmyArray.append(str1)myArray.append(str2)
To add them to the front:
//use 'insert' instead of appendmyArray.insert(str1, atIndex:0)myArray.insert(str2, atIndex:0)//Swift 3myArray.insert(str1, at: 0)myArray.insert(str2, at: 0)
As others have already stated, you can no longer use '+=' as of xCode 6.1
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.