Created
August 15, 2018 11:21
-
-
Save ChrisLawther/78f0e4d7bf0ece266470cb680eb534b0 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
// Following on from: | |
// https://gist.github.com/azureblue75/b28dfb0b12dd0e3a8139a92b9a0243ec | |
// ...and building on the approaches discussed in: | |
// https://talk.objc.io/episodes/S01E27-typed-notifications-part-1 | |
// Let's define a protocol for receiving system notifications: | |
protocol ReceivableNotification { | |
static var name: Notification.Name { get } | |
init(notification: Notification) | |
} | |
// Now we can define a struct to describe the dictionary passed in a system notification, | |
// for example a PlaygroundPageNeedsIndefiniteExecutionDidChangeNotification : | |
struct PlaygroundPayload { | |
let needsIndefiniteExecution: Bool | |
} | |
// And conform to our Receivable protocol: | |
extension PlaygroundPayload: ReceivableNotification { | |
static let name = Notification.Name("PlaygroundPageNeedsIndefiniteExecutionDidChangeNotification") | |
init(notification note: Notification) { | |
needsIndefiniteExecution = note.userInfo!["PlaygroundPageNeedsIndefiniteExecution"] as! Bool | |
} | |
} | |
// And finally, in a similar way as in our custom notifications approach, we'd like a way to register | |
// a handler for these notifications: | |
extension NotificationSource { | |
func addObserver<N: ReceivableNotification>(using block: @escaping (N) -> ()) -> Token { | |
return Token(token: addObserver(forName: N.name, object: nil, queue: nil, using: { note in | |
block(N.init(notification: note)) | |
}), center: self) | |
} | |
} | |
// Again, usage at the call site is then just: | |
token = NotificationCenter.default.addObserver { (note:PlaygroundPayload) in | |
print("Indefinite now: \(note.needsIndefiniteExecution)") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment