Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. SwiftBeginner - What are Arrays?

What are Arrays? - Images: Japanese

Hey there, everyone!

In the previous article we went over how to use variables and constants, so this time let's dig into arrays.

First, what is an 'array'? It's basically a way to manage data in a numbered sequence — think of it as a collection of variables (or constants) grouped together and assigned sequential numbers.

The two key points are that "variables (constants) are grouped together" and that "each one is given a sequential number." Arrays are sometimes called 'indexed arrays' for this reason.

It might sound a bit abstract, but imagine you want to store employee names and output the total count — it'd be much cleaner if you could group all those names together in one place. That's exactly when arrays come in handy.

Words can only go so far, so let's just define one and see what it looks like.

In Swift, there are a few ways to declare an array without initializing it. One way is to use the format arrayName: [DataType], like this:

var arr: [Int] // Declares the array 'arr'.

When declaring variables and constants, you'd write something like var n: Int. Here, you're just wrapping the type part in [].

There's also the arrayName: Array<Type> notation:

var arr: Array<Int>

Either one works fine. That said, the arrayName: [Type] style is less to type, so it seems to be the more common choice — though happy to be corrected on that.

Now, you can declare an array this way, but there's a catch — if you try to access an array that's only been declared (not initialized), you'll get an error.

var arr: [Int] // Declares the array 'arr'.

print(arr) // Error.

Same behavior as variables and constants.

So it's common practice to define an array while also initializing it, rather than just declaring it. There are a few ways to do this, and here's one of them:

var arr = [Int]()

Notice the () appended to [Type]. This defines the array while also initializing it.

You can also append () to Array<Type> and it works the same way:

var arr = Array<Int>()

Both [Type]() and Array<Type>() are valid, but [Type]() seems to be more widely used.

One thing to be careful about with this style: since you're assigning an instance of an array, you write [Type]() on the right side of =. It's not arrayName: [Type]() — watch out for that.

It's easy to mix up, so keep that in mind.

var arr: [Int]() // This is an error. The correct form is 'var arr = [Int]()', not 'var arr: [Int]()'. To just declare without initializing, use 'var arr: [Int]'.

You can also define an array by writing the values inside '[]' and assigning that directly:

var arr: [Int] = [1, 2, 3] // This works too. The '[]'-wrapped notation is sometimes called an 'array literal'.

// Think of it as similar to the following:
var s = "Hatsune Miku" // A String variable 's' is defined by initializing it with the string literal 'Hatsune Miku'.

This is the literal-style approach. The [] notation above is similar in concept to the " string literal — and it's called an array literal. You'll see this term come up in textbooks, so it's worth remembering.

In '[1, 2, 3]', the values 1, 2, and 3 are being put into the array 'arr'. Each value is separated by a ','.

One small note: in some other languages, writing a trailing comma like '[1, 2, 3,]' causes an error. In Swift, however, that trailing comma is perfectly fine.

var arr = [1, 2, 3,] // The trailing ',' is optional — both with and without are fine.

Also, just like with variables and constants, if you initialize an array using an array literal with one or more elements, you can omit the type annotation:

var arr = [1, 2, 3] // When passing one or more elements via an array literal like this, you don't need to specify the type with 'var arr: [Int]' or similar.

Same idea as with variables and constants.

Using an array literal also lets you avoid the error that occurs when trying to access a declaration-only array. Here's the problematic case again:

var arr: [Int] // Declares the array 'arr'.

print(arr) // Error.

You can sidestep this by assigning an empty array. Just assign []:

var arr: [Int] // Declares the array 'arr'.

arr = [] // Assign an empty array.

print(arr) // Outputs '[]'.

So when you want to just declare an array without populating it yet, the common approach is to initialize it with [] as the initial value, like this:

var arr: [Int] = [] // When you only want to declare the array 'arr', initialize it by passing '[]'.

print(arr) // Outputs '[]'.

One thing to note with this approach: when initializing with an empty array, you must specify the type.

var arr = [] // Error.

This is easy to get wrong, so be careful. Just add a type annotation and you're good:

var arr: [Int] = [] // OK.

var arr1 = [0, 1] // If you pass elements whose types are clear, the type annotation isn't needed.

Be careful not to redefine variables, arrays, or anything else using the same identifier — that will cause an error. Same rule applies in other languages too.

var s = ""

var s = 1 // Error.

So that covers the declaration and definition side of things.

Arrays in Swift are a bit more involved than in many recent languages, and there's quite a bit to take in — hopefully it hasn't been too overwhelming so far!

Next let's look at how to assign values to arrays and how to access them.

Earlier we assigned [1, 2, 3] to the array arr. To retrieve those values, you do this:

var arr = [1, 2, 3]

print(arr[0])

Take a look at the 'arr[0]' part inside 'print()'.

As shown above, you write [] right after the array name and put the number of the element you want to retrieve inside it.

In this case it says arr[0], so it outputs the 0th element of the array arr.

Now, "the 0th element?!" — you might be a bit thrown by that.

It takes some getting used to, but in programming, sequential numbering starts from 0. This is true in virtually every programming language, so go ahead and lock that in.

With that in mind, here are a few examples. Whether you're accessing or assigning, writing the number inside [] is always how it's done:

var arr = [1, 2, 3]

print(arr[0]) // Outputs the 0th element of array 'arr'. That's 1.

arr[1] = 100 // Changes the 1st element of array 'arr' to 100.

print(arr[1]) // Outputs 100.

let n = arr[1] + arr[2] // Adds the 1st and 2nd elements of array 'arr' and stores the result in constant 'n'.

print(n) // Outputs 103.

Let's also go over some terminology. The number you write inside [] when working with an array has a name — it's called an index, index number, or subscript. In the case of [1], the 1 is the index.

Each individual value stored in an array is called an 'element'. You'll run into this term constantly, so make sure it sticks.

Now let's go over a few important things to keep in mind when using arrays.

Think back to the array declaration and definition methods we covered. In each case, you were specifying a data type in some form.

If you saw that coming, good instincts — in Swift, arrays can basically only hold elements of the same type.

Let's try it out. We'll create a simple Int array:

var arr = [0, 1]

We assigned '[0, 1]' to 'arr', so this array is of type Int. Now let's try assigning a string to the 0th element:

var arr = [0, 1]

arr[0] = "" // Error.

Error. Trying to mix different types in an array literal will also get you yelled at:

var arr = [0, "Hatsune Miku"] // This won't fly either.

So in general, you can't mix types in an array.

That said, sometimes you really do want to put different types into one array.

For those cases, Swift provides a somewhat freewheeling type called Any. Here's how it works:

var arr: [Any] = [0, 3.14, "IA"]

This lets you throw in pretty much anything. However, when initializing with an array literal like this, you need to explicitly include ': [Any]' to tell Swift the type.

var arr: [Any] = [0, 3.14, "IA"] // This is fine.
var arr1 = [0, 3.14, "IA"] // This is not. You need ': [Any]'.

Swift can infer the type when all elements share the same type — like '[0, 1]' — but that doesn't work with 'Any'. Easy mistake to make, so watch out.

Also, if you want to use an element from an Any array in a calculation, you'll need to cast it first. Here's what happens without casting — this uses a regular Int array:

var arr = [0, 1, 2]

print(arr[0] + 1) // Outputs 1.

Now the same thing with an Any array:

var arr: [Any] = [0, 1, 2]

print(arr[0] + 1) // Error.

Error.

Swift generally doesn't allow arithmetic between values of different types, so the above throws an error.

To do the calculation, you need to cast the value first using 'as!' like this:

var arr: [Any] = [0, 1, 2]

var n = arr[0] as! Int // Cast it.

print(n + 1) // Outputs 1.

We'll cover cast and as! in a later article since they require some background knowledge — for now, just keep in mind that "arithmetic between different types isn't allowed."

Finally, using 'let' instead of 'var' gives you a read-only array whose contents can't be changed:

let arr = [0, 1]

With let, the contents become immutable:

let arr = [0, 1]

arr[0] = 3 // Error.

In most languages other than Swift, when you assign an array to a variable, the common convention is to call it an "array name" rather than a "variable name." Here's a JavaScript example:

var arr = [0, 1]; // Since an array is being assigned, 'arr' is typically called an array name rather than a variable name.

In Swift, however, regardless of what you assign to it, it's still called a variable — the convention is to say "assigning an array to a variable."

It's just a matter of terminology, but it might be worth keeping somewhere in the back of your mind.

Note that on this site we use the term "array name" in our explanations, so just keep that in mind as you read along.

And that covers the basics of arrays. This article ran pretty long — if you made it to the end, nice work!

In the next article, we'll look at adding and removing elements from arrays.

See you next time!

This article was written by Sakurama.

Author's beloved small mammal

桜舞 春人 Sakurama Haruto

A Tokyo-based programmer who has been creating various content since the ISDN era, with a bit of concern about his hair. A true long sleeper who generally feels unwell without at least 10 hours of sleep. His dream is to live a life where he can sleep as much as he wants. Loves games, sports, and music. Please share some hair with him.

If you find any errors or copyright issues, please .