Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple pubsub implementation in Swift
// =====================================================
enum LogLevel: Int {
case Debug = 1, Info, Error
}
let log_level = LogLevel.Debug
protocol Loggable {
func log()
func log_error()
func log_debug()
}
extension String: Loggable {
func log() {
if log_level.toRaw() <= LogLevel.Info.toRaw() {
println("[info]\t\(self)")
}
}
func log_error() {
if log_level.toRaw() <= LogLevel.Error.toRaw() {
println("[error]\t\(self)")
}
}
func log_debug() {
if log_level.toRaw() <= LogLevel.Debug.toRaw() {
println("[debug]\t\(self)")
}
}
}
// =====================================================
typealias Callback = () -> ()
struct Event {
static var events = Dictionary<String, Array<Callback>>()
static func register(event: String, callback: Callback) {
if !self.events[event] {
"Initializing list for event '\(event)'".log_debug()
self.events[event] = Array<Callback>()
}
if var callbacks = self.events[event] {
callbacks.append(callback)
self.events[event] = callbacks
"Registered callback for event '\(event)'".log_debug()
} else {
"Failed to register callback for event \(event)".log_error()
}
}
static func emit(event: String) {
"Emitting event '\(event)'".log_debug()
if let events = self.events[event] {
"Found list for event '\(event)', of length \(events.count)".log_debug()
for callback in events {
callback()
}
} else {
"Could not find callbacks for event '\(event)'".log_error()
}
}
}
// =====================================================
protocol Evented {
func emit(message: String) -> Bool
}
class Foo: Evented {
var name: String {
willSet(newName) {
self.emit("Name changed to \(newName)")
}
}
init(name: String) {
self.name = name
let evtName = "start"
Event.register(evtName) {
"The show is starting!".log()
}
}
func emit(message: String) -> Bool {
message.log_debug()
return true
}
}
// =====================================================
let myFoo = Foo(name: "Jahfer")
Event.emit("start")
myFoo.name = "Jeff"
myFoo.name = "Mary"
// Outputs:
// -----------------------------------------------------
// [debug] Initializing list for event 'start'
// [debug] Registered callback for event 'start'
// [debug] Emitting event 'start'
// [debug] Found list for event 'start', of length 1
// [info] The show is starting!
// [debug] Name changed to Jeff
// [debug] Name changed to Mary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.