Swift Tutorial: Getting Started with Arrays

Interested in learning Swift in the New Year? Excellent idea! Apple’s newer programming language for building iOS, macOS, and watchOS apps is more fully-featured and robust than ever, making it a perfect time to jump in.

In the past few months, we’ve covered everything from Swift strings to Swift Package Manager and the details of Swift 5.1. Now we’re going to tackle arrays, one of the core data types for Swift, which are extremely useful when arranging large datasets. When building with Swift, you will use them often.

What’s an Array, Anyway?

Glad you asked! An array is simply a way to organize a lot of data, assigned to a type. Here’s a straightforward example:

let numbers = [2, 5, 32, 11, 6, 843]

Take a look at the above code snippet, and you’ll see a few trends that dominate arrays in Swift. First, you’ll almost always want to assign an array as a constant (or let, in Swift-speak). Then you will assign your array a name (in this case, ‘numbers’), the equal-to sign, and values enclosed in brackets, separated by commas.

But values don’t always have to be numbers! You can also use strings… but make sure each string is in quotations, like so:

let names = [“Nate”, “Nick”, “Neil”]

(I’m sure the commas outside of the quotation marks are driving my editor mad, but they have to be that way!)

Empty Swift Arrays

The examples above are simple, straightforward Swift arrays. But you can get clever. For example, you can create empty arrays with just brackets:

var numbers2 = []

Here, we’ve assigned our array as a variable, or var. This is because we may want to add to it later, and assigning it as a variable allows us to play with it elsewhere in our code.

We can also assign the type of array we’d like to have. If we only wanted an empty array of doubles—numbers with up to two digits after the decimal point—we would assign it as such:

var numberDoubles: [Double] = []

Here, we’ve created a variable array and given it a name—but used a colon after the name to assign it a value. With arrays, assigned values must also be enclosed in brackets. If you don’t, you’ll see an error message like this:

Cannot convert value type of ‘[Any]’ to specified type ‘Double’

All Xcode is saying here is: “Look, if we’re gonna do the array thing, use brackets.” Appease the Xcode gods and use brackets when assigning a type, friends.

Accessing Arrays in Swift

Okay, cool, you’ve created an array. Now what? Now we access them!

Here are our numbers and names arrays, for reference:

let numbers = [2, 5, 32, 11, 6, 843]
let names = [“Nate”, “Nick”, “Neil”]

To access an array value, use brackets; just remember all arrays start at zero! So the number ‘2’ is .0 in an array. Let’s print a line:

print(“Give \(name[0]) $\(numbers[5]) already!”)

You just gave me $843. Thanks!

Here we’ve used string interpolation (the parentheses, much like the text between these parentheses that are meant as an interlude to a sentence) to insert our arrays. We use the brackets to access the value position of the arrays.

If you only wanted to give me $2, you’d have put numbers[0] and made me question our friendship forever. Good job.

If you need to access all of an array’s elements, use a for-loop. If you wanted to give Neil every dollar amount in your array, it would look something like this:

for number in numbers {
print(“Let’s give \(names[2]) \(number) dollars!”)
}

This would print separate lines, cycling through the numbers array, giving Neil the corresponding dollar amounts. Here, we’ve basically told Xcode that the ‘number’ for-loop will cycle through the numbers array for us so we don’t have to type separate print statements just to pay Neil too much. At least we’ve saved time!

Changing an Array

You could go back and change each array yourself, but that’s a ton of work, and not the most responsive way to do things. With a few in-line commands, you can change an array whenever you want.

Note: Any array you want open to manipulation must be assigned as a variable. Otherwise, you can’t change them elsewhere in your code. Tread lightly in such instances!

Let’s say we wanted to add a fourth name to our list. Because it’s a constant, we would have to go back and change it manually. If it were a variable, though, life would be much simpler. Here’s what we could do:

var names = [“Nate”, “Nick”, “Neil”]
names.append(“Norman”)

This appends Norman to the end of the list. But what if we had two or more people to add? Easy!

let names = [“Nate”, “Nick”, “Neil”, “Norman”]
names.append(contentsOf: [“Natalie”, “Nikita”])

This appends Natalie and Nikita to the end of the list. Neat! But hey, what if we wanted to have them in a certain order instead? We can use the insert function, and the array order:

names.insert(“Natalie”, at: 1)

That puts Natalie right after Nate. And removing someone? You guessed it: the remove function. Like so:

names.remove(at: 4)

Sorry, Norm!

Know Your Arrays

Arrays are mostly straightforward and basic, but mastering them is key. You’ll find yourself using them often for housing data; in many cases, you may have a large .swift file that is just an array—because your dataset is that large.

If you want to dive deeper into arrays, check out Apple’s documentation here.