【问题标题】:Swift - How to return a bool closureSwift - 如何返回一个布尔闭包
【发布时间】:2020-05-21 19:09:54
【问题描述】:

我正在尝试编写一个返回 Bool 的函数:

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

但我收到此错误:

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

我做错了什么?

【问题讨论】:

  • 1- 你的函数不返回Bool,它返回一个以Bool为参数并返回Void的闭包。 2- return { granted } 在定义为返回 Void 而不是 Bool 的闭包内调用。

标签: ios swift push-notification closures unusernotificationcenter


【解决方案1】:

你的函数返回类型很奇怪。我认为你想要做的是获得一个回调结果,以确定设备是否被授权接收推送通知。

您应该更改以下内容:

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

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

这样,您可以在确定推送权限后调用 registerForPushNotifications 并使用您希望运行的闭包。

registerForPushNotifications { granted in
  // Do something
}

【讨论】:

  • 谢谢。虽然看起来我们在完成之前需要@escaping:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-16
  • 1970-01-01
  • 2015-02-17
  • 2013-01-04
  • 2012-08-18
相关资源
最近更新 更多