vendredi 12 juin 2020

Switch statement instead of a ton of if statements

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()
}

Aucun commentaire:

Enregistrer un commentaire