How to add an element to the start of an Array in Swift?
You can use Array's
insert(_:at:) method to insert a new element at the start, or any other arbitrary position of an Array:
var array = ["world"] array.insert("hello", at: 0) // array is now ["hello", "world"]
Make sure that the position that you pass to the
at: argument isn't larger than the array's current last index plus one. For example:
// this is fine var array = ["hello"] array.insert("world", at: 1) // this will crash var array = ["hello"] array.insert("world", at: 2)
If you have any questions about this tip, or if you have feedback for me, don't hesitate to reach out on Twitter.