DEV Community

Gamya
Gamya

Posted on

Swift Arrays

So far in our Swift journey, we've worked with single values — a name here, a number there. But what happens when you need to store a whole squad of values? 🤔

That's where arrays come in.


🧠 Why Do Arrays Exist?

Imagine you're building an app that tracks all the characters from Attack on Titan. You could do this:

let character1 = "Eren"
let character2 = "Mikasa"
let character3 = "Armin"
let character4 = "Levi"
Enter fullscreen mode Exit fullscreen mode

Sure, that works for four characters. But what about all 100+ members of the Survey Corps? 😅 That approach falls apart fast.

This is exactly why Swift gives us arrays — a single place to store as many values as you need, always in the order you added them.


📦 Creating Your First Array

Arrays use square brackets [], with commas between each item:

var surveyCorps = ["Eren", "Mikasa", "Armin", "Levi"]
let episodeCounts = [13, 12, 22, 16, 28]
var ratings = [9.8, 8.7, 9.5, 7.6]
Enter fullscreen mode Exit fullscreen mode

Three things to notice here:

  • Strings → wrapped in quotes ""
  • Integers → plain numbers
  • Doubles → numbers with a decimal point

Swift is smart enough to figure out the type of each array just by looking at what's inside. 🧐


🔢 Reading Values — Zero Indexing

Here's the part that trips up almost every beginner (don't worry, it gets natural fast):

Arrays in Swift start counting from 0, not 1.

This is called zero-based indexing. So:

Position Index Value
1st [0] "Eren"
2nd [1] "Mikasa"
3rd [2] "Armin"
4th [3] "Levi"
print(surveyCorps[0]) // Eren
print(surveyCorps[1]) // Mikasa
print(surveyCorps[3]) // Levi
Enter fullscreen mode Exit fullscreen mode

⚠️ Watch out! If you try to access an index that doesn't exist, Swift will crash your app on purpose. For example:

print(surveyCorps[99]) // 💥 CRASH
Enter fullscreen mode Exit fullscreen mode

That might sound scary, but it's actually Swift protecting you. If it didn't crash, you'd silently get back garbage data — which is way worse than a crash you can see and fix. Think of it as Swift saying "Hey! That character doesn't exist in this arc!" 😤


➕ Adding Items to an Array

If your array is a var (variable), you can keep adding to it using .append():

var surveyCorps = ["Eren", "Mikasa", "Armin"]

surveyCorps.append("Levi")
surveyCorps.append("Hange")
surveyCorps.append("Connie")

print(surveyCorps)
// ["Eren", "Mikasa", "Armin", "Levi", "Hange", "Connie"]
Enter fullscreen mode Exit fullscreen mode

You can even append the same value more than once — Swift won't stop you:

surveyCorps.append("Eren") // Eren again? Okay then 😅
Enter fullscreen mode Exit fullscreen mode

🚫 Type Safety — One Type Per Array

Swift is very strict about this: an array can only hold one type of data.

var ratings = [9.8, 8.7, 9.5]
ratings.append("Mikasa") // ❌ ERROR — can't add a String to a Double array
Enter fullscreen mode Exit fullscreen mode

This is type safety in action. Once Swift knows your array holds Double values, it won't let anything else sneak in. This keeps your data clean and your app stable. 🔒


🏗️ Creating Empty Arrays

Sometimes you don't have data yet — you want to start empty and fill it in as you go. Here are two ways to do that:

Explicit syntax:

var titanShifters = Array<String>()
titanShifters.append("Attack Titan")
titanShifters.append("Armored Titan")
titanShifters.append("Colossal Titan")
Enter fullscreen mode Exit fullscreen mode

Shorthand syntax (more common):

var titanShifters = [String]()
titanShifters.append("Attack Titan")
titanShifters.append("Armored Titan")
titanShifters.append("Colossal Titan")
Enter fullscreen mode Exit fullscreen mode

Both do exactly the same thing. The second one is what you'll see most in the wild. 🌿


🛠️ Useful Array Operations

📏 Count — How many items?

var surveyCorps = ["Eren", "Mikasa", "Armin", "Levi"]
print(surveyCorps.count) // 4
Enter fullscreen mode Exit fullscreen mode

🗑️ Remove Items

var titans = ["Attack", "Armored", "Colossal", "Beast", "War Hammer"]

titans.remove(at: 2)   // Removes "Colossal"
print(titans.count)    // 4

titans.removeAll()     // Wipes everything
print(titans.count)    // 0
Enter fullscreen mode Exit fullscreen mode

🔍 Check if Something Exists — contains()

let seasons = ["Season 1", "Season 2", "Season 3", "The Final Season"]
print(seasons.contains("Season 4"))          // false
print(seasons.contains("The Final Season"))  // true
Enter fullscreen mode Exit fullscreen mode

🔤 Sort Your Array — sorted()

let characters = ["Reiner", "Annie", "Bertholdt", "Zeke"]
print(characters.sorted())
// ["Annie", "Bertholdt", "Reiner", "Zeke"]
Enter fullscreen mode Exit fullscreen mode

sorted() returns a new sorted array — the original stays unchanged. Neat! ✨

For numbers, it sorts smallest → largest:

let episodes = [7, 1, 22, 13, 4]
print(episodes.sorted()) // [1, 4, 7, 13, 22]
Enter fullscreen mode Exit fullscreen mode

🔄 Reverse an Array — reversed()

let arcs = ["Trost", "Female Titan", "Clash of Titans", "Return to Shiganshina"]
let reversed = Array(arcs.reversed())
print(reversed)
// ["Return to Shiganshina", "Clash of Titans", "Female Titan", "Trost"]
Enter fullscreen mode Exit fullscreen mode

💡 Pro tip: Swift doesn't actually rearrange the items when you call reversed(). It just remembers you want them reversed — lazy in the best possible way. Wrapping it in Array() gives you a plain array back.


🧩 Putting It All Together

Here's a mini program using everything we covered:

// Starting lineup
var squadMembers = ["Eren", "Mikasa", "Armin"]

// Add more members
squadMembers.append("Levi")
squadMembers.append("Hange")

// Check the roster
print("Squad size: \(squadMembers.count)") // 5

// Is Zeke in the squad?
print(squadMembers.contains("Zeke")) // false

// Sort alphabetically
print(squadMembers.sorted())
// ["Armin", "Eren", "Hange", "Levi", "Mikasa"]

// Remove Eren (he went rogue 😬)
squadMembers.remove(at: 0)
print(squadMembers.count) // 4
Enter fullscreen mode Exit fullscreen mode

🧵 Quick Recap

Feature What it does Example
[] Create an array var names = ["A", "B"]
[0] Access by index names[0]
.append() Add an item names.append("C")
.count Total items names.count
.contains() Check existence names.contains("A")
.sorted() Sort (new array) names.sorted()
.reversed() Reverse (new array) names.reversed()
.remove(at:) Remove by index names.remove(at: 0)
.removeAll() Wipe the array names.removeAll()

🎯 Why This Matters

Arrays are everywhere in real apps. Every list you see on screen — messages, contacts, search results, leaderboards — is backed by an array under the hood. Getting comfortable with them early is one of the best investments you can make as a Swift developer. 💪

Next up, we'll look at dictionaries — another way to store data, but with labels instead of positions. See you there! 👋


Top comments (0)