A Swifty approach to notification based programming
Sometimes when wanting to know when a value has changed, it can be difficult to write clean, safe code that won't introduce weird behaviors like firing multiple times. SwiftyBind attempts to solve this problem by encapsulating the logic firing notifications. Heres an example:
struct Michelle {
private var spilledTheMilkBinder = SwiftyBind(false)
var spilledTheMilk {
return spilledTheMilkBinder.interface
}
func spillMilk() {
spilledTheMilk.value = true
}
}
protocol FullHouseParent: class {
var michelle: Michelle { get }
init(michelle: Michelle)
}
final class BobSaget: FullHouseParent {
var michelle: Michelle
init(michelle: Michelle) {
self.michelle = michelle
self.michelle.spilledTheMilk.bind {
if $0 { print("Oh no, why is there milk all over Comet!") }
}
}
}
let michelle = Michelle()
let bobSaget = BobSaget(michelle)
michelle.spillMilk()
In the example, notice how when spillMilk
is invoked on the Michelle
instance, this will notify the registered closure only once.
You can add SwiftyBind to your Package.swift
file like so:
dependencies: [
.package(url: "https://github.com/eman6576/SwiftyBind.git", from: "1.0.0")
]
SwiftyBind is released under the MIT license. See LICENSE for details.