Creating arrays

The easiest way to create an array is by using an array literal, which is a concise way to provide array values. An array literal is a list of values separated by commas and surrounded by square brackets:

let evenNumbers = [2, 4, 6, 8]

Since the array literal only contains integers, Swift infers the type of evenNumbers to be an array of Int values. This type is written as [Int]. The type inside the square brackets defines the type of values the array can store, which the compiler will enforce when you add elements to the array. If you try to add a string, for example, the compiler will return an error and your code won’t compile.

An empty array can be created using the empty array literal []. Because the compiler isn’t able to infer a type from this, you need to use a type annotation to make the type explicit:

var subscribers: [String] = []

It’s also possible to create an array with all of its values set to a default value:

let allZeros = Int

// > [0, 0, 0, 0, 0]

Since [Int] — including the square brackets — is just a type, you’re calling its initializer in this example. Initializers are special functions you use to create values. You’ve already seen them used for type conversion in Chapter 3 and will learn more about them in Chapter 13.

What about type inference? The parameter repeating: 0 can be type inferred by the compiler to be an Int so you can also write:

let allZerosInferred = Array(repeating: 0, count: 5)

// > [0, 0, 0, 0, 0]

If you option-click on allZerosInferred you will see that it is also [Int].

Finally, remember that it’s good practice to declare arrays that aren’t going to change as constants. For example, consider this array:

let vowels = ["A", "E", "I", "O", "U"]

vowels is an array of strings and its values can’t be changed. But that’s fine, since the list of vowels doesn’t tend to change very often!

results matching ""

    No results matching ""