Forked from chriseidhof/TypedNotifications.swift
Last active
February 24, 2016 19:09
-
-
Save Morse-Code/73d4d12cb711ccf111a5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
class Box<T> { | |
let unbox: T | |
init(_ value: T) { self.unbox = value } | |
} | |
struct Notification<A> { | |
let name: String | |
} | |
func postNotification<A>(note: Notification<A>, value: A) { | |
let userInfo = ["value": Box(value)] | |
NSNotificationCenter.defaultCenter().postNotificationName(note.name, object: nil, userInfo: userInfo) | |
} | |
class NotificationObserver { | |
let observer: NSObjectProtocol | |
init<A>(notification: Notification<A>, block aBlock: A -> ()) { | |
observer = NSNotificationCenter.defaultCenter().addObserverForName(notification.name, object: nil, queue: nil) { note in | |
if let value = (note.userInfo?["value"] as? Box<A>)?.unbox { | |
aBlock(value) | |
} else { | |
assert(false, "Couldn't understand user info") | |
} | |
} | |
} | |
deinit { | |
NSNotificationCenter.defaultCenter().removeObserver(observer) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment