Notice: Undefined index: understanding-swift in /var/sites/hackingwithswift.com/site/src/Controller/NewBooksReadController.php on line 89
Why does Swift have arrays? - a free tutorial

NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

Why does Swift have arrays?

Paul Hudson    @twostraws   

Swift’s strings, integers, Booleans, and Doubles allow us to temporarily store single values, but if you want to store many values you will often use arrays instead.

We can create constants and variables of arrays just like other types of data, but the difference is that arrays hold many values inside them. So, if you want to store the names of weekdays, the temperature forecast for the next week, or the high scores for a video game, you’ll want an array rather than a single value.

Arrays in Swift can be as large or as small as you want. If they are variable, you can add to them freely to build up your data over time, or you can remove or even rearrange items if you want.

We read values out of arrays using their numerical position, counting from 0. This “counting from 0” has a technical term: we can say that Swift’s arrays are zero-based. Swift will automatically crash your program if you attempt to read an array using an invalid index. For example, creating an array with three items then trying to read index 10.

I know what you’re thinking: an app crash is bad, right? Right. But trust me: if Swift didn’t crash then it’s very likely you would get back bad data, because you tried to read a value outside what your array holds.

Hacking with Swift is sponsored by NSSpain

SPONSORED Announcing NSSpain 2020: Remote Edition! An online, continuous conference for iOS developers. We’ll start on Thursday and finish on Friday, with talks, activities, and lots of fun for 36 hours, non-stop. Sound good? Join us!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Link copied to your pasteboard.