How to add an element to the start of an Array in Swift?

Published by donnywals on

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.


Practical Combine

Learn everything you need to know about Combine and how you can use it in your projects with my new book Practical Combine. You'll get thirteen chapters, a Playground and a handful of sample projects to help you get up and running with Combine as soon as possible.

The book is available as a digital download for just $24.99!

Get Practical Combine

Receive weekly updates about my posts

Categories: Swift Tips