Learn
Arrays
Creating an Array Literal

We learned one way to create an array, but there’s another.

We can also declare and initialize an array with a list of values, separated by commas, and surrounded by a pair of square brackets.

The syntax to create an array this way looks like:

var name = [list of values]

Suppose we want to create an array called location with Codecademy HQ’s latitude and longitude:

var location = [40.7245, -73.9979]

Due to Swift’s built-in type inference, the type of the array is inferred. To be explicit:

var location: [Double] = [40.7245, -73.9979]

Let’s try creating arrays using this new approach.

Instructions

1.

Suppose the Tokyo Subway costs are as follows:

Ticket Adult Child
24-hour Β₯800 Β₯400
48-hour Β₯1200 Β₯600
72-hour Β₯1500 Β₯750

Create an array named subwayAdult and initialize it with 800, 1200, and 1500.

Print it out using print().

2.

Initialize subwayChild with 400, 600, and 750. This time, be explicit with the type.

Then print it out.

Folder Icon

Take this course for free

Already have an account?