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?
let array = [Int]()
you can never sayarray[0] = 42
It will give index out of range error. You should usearray.append(42)
. Why can't you subscript? For the same reason you can't doletters[3] = d
forlet letters = [a,b,c]
. The 3rd index is non-existent as is array[0] before a value!