Adding Elements to an Array

If you have an array of prime numbers and want to add a new prime number to the list, you can use Swift’s append method, like this:

var primes = [2,3,5,7,11,13,17,19,23,29]primes.append(31) // [2,3,5,7,11,13,17,19,23,29,31]

Note

If you have appended to an array in Python before, you know that Python also uses append to add to arrays. You will see some things in Swift from other languages from time to time.

You can also use += to easily concatenate two arrays:

raining += ["dogs","pigs","wolves"] // ["cats","dogs","pigs","wolves"]

When you append to an array, you are adding an element to the end of an array. The element you append will always become the last ...

Get Learning Swift™ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.