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

Published on: January 19, 2020
Updated on: April 23, 2024

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.

Expand your learning with my books

Practical Swift Concurrency header image

Learn everything you need to know about Swift Concurrency and how you can use it in your projects with Practical Swift Concurrency. It contains:

  • Eleven chapters worth of content.
  • Sample projects that use the code shown in the chapters.
  • Free updates for future iOS versions.

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

Learn more