简体   繁体   English

Swift - 如何返回布尔闭包

[英]Swift - How to return a bool closure

I'm trying to write a function that returns a Bool:我正在尝试编写返回 Bool 的 function:

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?我究竟做错了什么?

Your function return type is weird.您的 function 返回类型很奇怪。 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

registerForPushNotifications { granted in
  // Do something
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM