Swift Collections

Swift Collections

·

3 min read

Hello fellas 🥳 this is my first post about swift. In this article, I will try to write about some swift collections. I know actually Apple documents are very good about this topic. I just wanted to write something.

Topics: Iterating, Filter, Reduce, Zip

Have fun 🙂

Iterating

If I want to iterate through an array, I can put it in a for loop then print out each item in it.

let animals = ["Antelope", "Butterfly", "Camel", "Dolphin"]

for animal in animals {
    print(animal)
}
// Prints "Antelope"
// Prints "Butterfly"
// Prints "Camel"
// Prints "Dolphin"

Or I can use IteratorProtocol for the same output. Here I created a variable for calling animals with start iterator and I used the next function to get the next value in the animals array.

var animalIterator = animals.makeIterator()
while let animal = animalIterator.next() {
    print(animal)
}
// Prints "Antelope"
// Prints "Butterfly"
// Prints "Camel"
// Prints "Dolphin"

Example for IteratorProtocol

struct CountdownIterator: IteratorProtocol {
    let countdown: Countdown
    var times = 0

    init(_ countdown: Countdown) {
        self.countdown = countdown
    }

    mutating func next() -> Int? {
        let nextNumber = countdown.start - times
        guard nextNumber > 0
            else { return nil }

        times += 1
        return nextNumber
    }
}

if you want to get more detail about the IteratorProtocol visit here

Filter

The filter method helps us while using an array. This example show names shorter than five characters.

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let shortNames = cast.filter { $0.count < 5 }
print(shortNames)
// Prints "["Kim", "Karl"]"

Another filter example: I produced Pokemon mock data and used the filter function to eliminate one data. After eliminating we used the enumerated() method with forEach to show data.

struct Pokemon {
    let name: String
    let type: String
}

var pokemons = [
    Pokemon(name: "Pikachu", type: "Electric"),
    Pokemon(name: "Charizard", type: "Fire"),
    Pokemon(name: "Balbasar", type: "Grass"),
]

let pokemonToRemove = Pokemon(name: "Pikachu", type: "Electric")

pokemons = pokemons.filter { poke in
    return poke.name != pokemonToRemove.name
}

pokemons.enumerated().forEach { (index, poke) in
    print("Pokemon at \(index) has a name \(poke.name)")
}

print(pokemons)
// Pokemon at 0 has a name Charizard
// Pokemon at 1 has a name Balbasar
  • if you want to get more detail about the filter method visit here
  • if you want to get more detail about the enumerated method visit here

Reduce

Returns the result of combining the elements of the sequence using the given closure.

I created variadic generic here to calculate numbers. Here reduce(0) means it starts the calculation from scratch.

func calculateNumbers<T: Numeric>(_ numbers: T...) -> T {
    return numbers.reduce(0) { $0 + $1 }
}

calculateNumbers(1, 2.5, 3, 4, 5, 6, -1, 8, -0.5) //28

Real word example with reduce.


struct Item {
    let name: String
    let price: Double
}

struct Cart {

    private(set) var items: [Item] = []

    mutating func addItem(_ item: Item) {
        items.append(item)
    }

    var total: Double {
        items.reduce(0) { (value, item) -> Double in
            return value + item.price
        }
    }
}

var cart = Cart()
cart.addItem(Item(name: "Milk", price: 4.50))
cart.addItem(Item(name: "Bread", price: 2.50))
cart.addItem(Item(name: "Eggs", price: 12.50))

print(cart.total) //19.5

Example with reduce into

let letters = "abracadabra"
let letterCount = letters.reduce(into: [:]) { counts, letter in
    counts[letter, default: 0] += 1
}
// letterCount == ["a": 5, "b": 2, "r": 2, "c": 1, "d": 1]

if you want to get more detail about the reduce visit here and here

Zip

Creates a sequence of pairs built out of two underlying sequences.

let students = ["Joey Tribbiani", "Rachel Greene", "Ross Geller", "Monica Geller", "Phoebe Buffay"]
let grades = [9, 8.8, 10]

let pair = zip(students, grades)

for studentAndGrade in pair {
    print(studentAndGrade.0)
    print(studentAndGrade.1)
}

/*
Joey Tribbiani
9.0
Rachel Greene
8.8
Ross Geller
10.0
*/

if you want to get more detail about the zip visit here

Â