Skip to content

Instantly share code, notes, and snippets.

@JoshuaSullivan
Last active April 8, 2020 18:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JoshuaSullivan/cb6d0c6dcfde3f20b43b to your computer and use it in GitHub Desktop.
Save JoshuaSullivan/cb6d0c6dcfde3f20b43b to your computer and use it in GitHub Desktop.
Don't use Swift enums to box magic strings! Read the blog post: http://www.chibicode.org/?p=16
enum NotificationNames: String {
case UserDataChanged: "UserDataChangedNotificationName"
case ReceivedAlert: "ReceivedAlertNotificationName"
case PeanutButterJellyTime: "ItsPeanutButterJellyTimeNotificationName"
}
struct NotificationNames {
static let userDataChanged = "UserDataChangedNotificationName"
static let receivedAlert = "ReceivedAlertNotificationName"
static let peanutButterJellyTime = "ItsPeanutButterJellyTimeNotificationName"
}
// Using the enum:
NSNotificationCenter.defaultCenter().postNotificationName(NotificationNames.UserDataChanged.rawValue, object:nil)
// Using the struct
NSNotificationCenter.defaultCenter().postNotificationName(NotificationNames.userDataChanged, object:nil)
// If you need switching, remember that Swift can switch on just about any comparison type:
func handleNotification(note: NSNotification) {
switch note.name {
case NotificationNames.userDataChanged: print("User data changed!")
case NotificationNames.receivedAlert: print("WHAT!? An alert!")
case NotificationNames.peanutButterJellyTime: print("Where ya at? Where ya at? Where ya at?")
default: print("I have no idea what's going on.")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment