I'm currently working with notifications and wanna print out an identifier. How can I replace all if-statements with one switch?
Here is my enum that keeps all identifier with corresponding string value:
enum NotificationIdentifier:String {
case local = "Local Notification"
case localWithAction = "Local Notification with Action"
case localWithContent = "Local Notification with Content"
case pushWithAPNs = "Push Notification with APNs"
case pushWithFirebase = "Push Notification with Firebase"
case pushWithContent = "Push Notification with Content"
}
And my delegate method:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if response.notification.request.identifier == NotificationIdentifier.local.rawValue {
print("Handling notification with the \(NotificationIdentifier.local.rawValue)")
} else if response.notification.request.identifier == NotificationIdentifier.localWithAction.rawValue {
print("Handling notification with the \(NotificationIdentifier.localWithAction.rawValue)")
} else if response.notification.request.identifier == NotificationIdentifier.localWithContent.rawValue {
print("Handling notification with the \(NotificationIdentifier.localWithContent.rawValue)")
} else if response.notification.request.identifier == NotificationIdentifier.pushWithAPNs.rawValue {
print("Handling notification with the \(NotificationIdentifier.pushWithAPNs.rawValue)")
} else if response.notification.request.identifier == NotificationIdentifier.pushWithFirebase.rawValue {
print("Handling notification with the \(NotificationIdentifier.pushWithFirebase.rawValue)")
} else {
print("Handling notification with the \(NotificationIdentifier.pushWithContent.rawValue)")
}
completionHandler()
}
Initialize the enum
of NotificationIdentifier
and use switch case like below:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
guard let notificationIdentifier = NotificationIdentifier(rawValue: response.notification.request.identifier) else { return }
switch notificationIdentifier {
case .local:
print("Handling notification with the \(NotificationIdentifier.local.rawValue)")
case .localWithAction:
print("Handling notification with the \(NotificationIdentifier.localWithAction.rawValue)")
case .localWithContent:
print("Handling notification with the \(NotificationIdentifier.localWithContent.rawValue)")
case .pushWithAPNs:
print("Handling notification with the \(NotificationIdentifier.pushWithAPNs.rawValue)")
case .pushWithFirebase:
print("Handling notification with the \(NotificationIdentifier.pushWithFirebase.rawValue)")
case .pushWithContent:
print("Handling notification with the \(NotificationIdentifier.pushWithContent.rawValue)")
}
}