How to add an element to the start of an Array in Swift?Published on: January 19, 2020
You can use Array's
insert(_:at:) method to insert a new element at the start, or any other arbitrary position of an Array:
In-app purchases made easy. RevenueCat provides everything you need to implement, manage, and analyze in-app purchases without managing servers or writing backend code.
Try RevenueCat now
This sponsored message helps keep the content on this site free. Please check out this sponsor as it directly supports me and this site.
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.