Skip to content

Instantly share code, notes, and snippets.

@donpark
Created December 2, 2016 18:17
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donpark/5e2d972b7e926237a74c7818fb04cbdc to your computer and use it in GitHub Desktop.
Save donpark/5e2d972b7e926237a74c7818fb04cbdc to your computer and use it in GitHub Desktop.
How to use enum of Notification.Name

Adding NotificationEnum.swift file to your project enables declaring enum of Notification.Name like this:

enum MyEvent: Notification.Name {
case foo = "foo"
case bar = "bar"
}

To send notification:

NotificationCenter.default.post(name: MyEvent.foo.rawValue, ...)

To observe:

NotificationCenter.default.addObserver(..., name: MyEvent.foo.rawValue)

To switch on notification.name:

switch MyEvent(rawValue: notification.name) {
case .foo:
    break
case .bar:
    break
}
import Foundation
// Extension allowing enum of Notification.Names.
#if swift(>=3.0)
extension Notification.Name: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(value)
}
public init(unicodeScalarLiteral value: String) {
self.init(value)
}
}
#else
extension Notification.Name: StringLiteralConvertible {
public init(stringLiteral value: String) {
self.init(value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(value)
}
public init(unicodeScalarLiteral value: String) {
self.init(value)
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment