Arrays
Ordered, type-safe collections — creating, mutating, and iterating over an Array.
읽는 데 2분
An Array is an ordered collection of values, all of the same type. That last part matters more in Swift than in many languages: you can't mix a String and an Int in the same array by accident.
var scores: [Int] = [90, 85, 78]
var names = ["Ada", "Grace", "Sam"] // inferred as [String]
// var mixed = [1, "two", 3.0] // error — no single inferred element type[Int] is shorthand for Array<Int> — you'll see both forms, but the bracket syntax is far more common in everyday code.
Adding, removing, and accessing elements
var groceries = ["milk", "eggs"]
groceries.append("bread") // ["milk", "eggs", "bread"]
groceries.insert("butter", at: 1) // ["milk", "butter", "eggs", "bread"]
groceries.remove(at: 0) // removes "milk"
let first = groceries.first // "butter", as an Optional<String>
let last = groceries.last // "bread", as an Optional<String>
print(groceries[0]) // "butter" — direct indexing, but crashes if out of boundsNotice .first and .last return optionals (String?), not a plain String — an empty array has no first element, so Swift makes that possibility explicit rather than crashing or returning a placeholder value. Direct subscripting (groceries[0]), by contrast, crashes immediately on an out-of-bounds index, so it's best reserved for cases where you've already confirmed the index is valid.
Iterating and transforming
let numbers = [1, 2, 3, 4, 5]
for number in numbers {
print(number)
}
let doubled = numbers.map { $0 * 2 } // [2, 4, 6, 8, 10]
let evens = numbers.filter { $0 % 2 == 0 } // [2, 4]
let total = numbers.reduce(0) { $0 + $1 } // 15map, filter, and reduce are higher-order functions (functions that take another function as an argument) that transform a collection without you writing a manual loop. $0 and $1 refer to a closure's first and second arguments — closures get a full lesson shortly, but this is a preview of how naturally they show up with collections.
Checking contents and size
let fruits = ["apple", "banana"]
print(fruits.count) // 2
print(fruits.isEmpty) // false
print(fruits.contains("apple")) // trueAlways prefer .isEmpty over .count == 0 — it reads more clearly and, for some collection types, is meaningfully faster to check. Arrays are the workhorse collection in Swift; the next lesson covers Dictionary and Set, the other two you'll reach for constantly.