Skip to content

Swift Arrays

Whether an array is empty

swift
var exampleArray = [1,2,3,4,5]
exampleArray.isEmpty //false

Return an array’s size

swift
var exampleArray = [1,2,3,4,5]
exampleArray.count //5

Reverse an array

swift
var exampleArray = [1,2,3,4,5] 
exampleArray.reverse() //reverse in place
let newArray = exampleArray.reversed() //return a new array

Filter an array

swift
let numbers = [22, 41, 23, 30]
let evenNumbers = numbers.filter { $0 % 2 == 0 }

struct Person {
    var age : Int
}
let people = [Person(age: 22), Person(age: 41), Person(age: 23), Person(age: 30)]
let peopleYoungerThan30 = people.filter { $0.age < 30 }

Insert a new element at index

swift
var numbers = [1, 2, 3, 4, 5]
numbers.insert(100, at: 3)
numbers.insert(200, at: numbers.endIndex)

Append a new element at the end of array

swift
var numbers = [1, 2, 3, 4, 5]
numbers.append(100)

References