soleil
soleil

Reputation: 13085

Swift - How to return a bool closure

I'm trying to write a function that returns a Bool:

func registerForPushNotifications() -> (Bool) -> Void {
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
        [weak self] granted, error in
        return { granted }
    }
}

But I get this Error:

Cannot convert return expression of type 'Void' to return type '(Bool) -> Void'

What am I doing wrong?

Upvotes: 0

Views: 2837

Answers (1)

AdamPro13
AdamPro13

Reputation: 7400

Your function return type is weird. I think what you're trying to do is get a callback with the result for whether or not the device is authorized to receive push notifications.

You should change the following:

func registerForPushNotifications() -> (Bool) -> Void {
   // Your implementation
}

to

func registerForPushNotifications(completion: (Bool) -> Void) {
   UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] granted, error in
      completion(granted)
   }
}

This way, you can call registerForPushNotifications with a closure you wish to run after push permissions have been determined.

registerForPushNotifications { granted in
  // Do something
}

Upvotes: 1

Related Questions