Menu
Coddy logo textTech

Declaring An Array

Part of the Fundamentals section of Coddy's Swift journey — lesson 62 of 86.

So far, you've worked with individual values stored in variables. But what if you need to store a list of items—like a collection of scores, names, or prices? That's where arrays come in.

An array is an ordered collection that holds multiple values of the same type. You can create an array by placing values inside square brackets, separated by commas:

let fruits = ["Apple", "Banana", "Orange"]
let scores = [85, 92, 78, 95]

Swift automatically infers the array's type from its values. In the examples above, fruits is an array of strings ([String]), and scores is an array of integers ([Int]).

You can also declare an array with an explicit type annotation:

var prices: [Double] = [9.99, 14.50, 3.25]

To create an empty array, you need to specify the type since Swift can't infer it from the values:

var names: [String] = []
var numbers = [Int]()

Both approaches create an empty array ready to hold values of the specified type.

challenge icon

Challenge

Easy

Create three different arrays to represent a small inventory system:

  1. An array of strings called products containing: "Laptop", "Mouse", "Keyboard"
  2. An array of integers called quantities containing: 5, 20, 15
  3. An empty array of doubles called prices with an explicit type annotation

After declaring all three arrays, print each one on a separate line in the order listed above.

For example, your output should be:

["Laptop", "Mouse", "Keyboard"]
[5, 20, 15]
[]

Cheat sheet

An array is an ordered collection that holds multiple values of the same type. Create arrays by placing values inside square brackets, separated by commas:

let fruits = ["Apple", "Banana", "Orange"]
let scores = [85, 92, 78, 95]

Swift automatically infers the array's type from its values. You can also use explicit type annotations:

var prices: [Double] = [9.99, 14.50, 3.25]

To create an empty array, specify the type:

var names: [String] = []
var numbers = [Int]()

Try it yourself

// TODO: Write your code below

// 1. Create an array of strings called 'products' with: "Laptop", "Mouse", "Keyboard"

// 2. Create an array of integers called 'quantities' with: 5, 20, 15

// 3. Create an empty array of doubles called 'prices' with explicit type annotation

// Print each array on a separate line
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals