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:
Looking for a great mobile CI/CD solution that has tons of iOS-specific tools, smooth code signing, and even real device testing? Learn more about Bitrise’s iOS specific solutions.
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.