Grant Emerson

Different Days

Different Days β€” SwiftMoji Entry #10

Swift 5.1 added the capability to diff any two BidirectionalCollections with equivalent Element types. The function is called difference(from:) and it has two parameters. The first is labeled from and it indicates the starting state from which to calculate the changes necessary to convert it to be equal to the state of the caller. Although not needed if the Elements are Equatable, the difference function has a second parameter labeled by which is a closure taking two elements and returning a boolean based on equivalence. In the following example, two Arrays are initialized with a collection of calendar items. These Arrays represent a summer and winter schedule. When the difference function is called on winterSchedule with a base state of summerSchedule, the resulting CollectionDifference contains one removal for mowing grass and two insertions for shoveling and starting the fireplace.

import Foundation

struct πŸ—“: Equatable {
    let title: String
    let date: Date
}

extension Date {
    static let dateFormatter: DateFormatter = {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "h:mm a"
        return dateFormatter
    }()
    
    init(_ text: String) {
        self = Self.dateFormatter.date(from: text)!
    }
}

let summerSchedule = [
    πŸ—“(title: "Eat 🍳", date: Date("7:00 AM")),
    πŸ—“(title: "πŸš— to 🏒", date: Date("9:00 AM")),
    πŸ—“(title: "Eat 🍽", date: Date("5:00 PM")),
    πŸ—“(title: "Mow 🌱", date: Date("6:00 PM"))
]

let winterSchedule = [
    πŸ—“(title: "Eat 🍳", date: Date("7:00 AM")),
    πŸ—“(title: "Shovel Driveway", date: Date("8:00 AM")),
    πŸ—“(title: "πŸš— to 🏒", date: Date("9:00 AM")),
    πŸ—“(title: "Eat 🍽", date: Date("5:00 PM")),
    πŸ—“(title: "Start πŸ”₯place", date: Date("6:00 PM"))
]

let changes = winterSchedule.difference(from: summerSchedule)
let summerOnlyTasks = changes.removals.count // 1
let winterOnlyTasks = changes.insertions.count // 2
Tagged with: