在Swift 3中,如果没有更多的上下文信息,表达式的类型是不明确的。

3

我正在尝试学习Swift,并通过推送通知教程进行学习。

let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge , .Sound], categories: nil)

在 Xcode 8 中遇到了问题:

"Type of expression is ambiguous without more context".

我将这一行代码从教程中复制粘贴而来,也在 StackOverFlow 上看到相同的代码。

我做错了什么?
请注意,错误信息中出现了 HTML 标签。


我想这个野兽在那边? ;) http://balancedcode.com/blog/files/de01930f6f2cf9e4c886531eca028cba-0.html 我不得不使用xCode的Swift 3提示来处理它。 - Alex Hall
2个回答

11

查看 UIUserNotificationSettings 的文档。它的签名在 Swift 3 中已更改,类型的值也已更改。

你需要:

let settings = UIUserNotificationSettings(types: [.alert, .badge , .sound], categories: nil)

当然,如果您只支持iOS 10及以上版本,则不应使用UIUserNotificationSettings,因为它现在已被弃用。请改用UNNotificationSettings。但是,如果您仍在支持iOS 9或更早版本,则只要更改为更新的语法,使用UIUserNotificationSettings也可以。


非常感谢,Maddy。我知道iOS 10及更高版本应该使用UNNotificationSettings类,但我刚刚开始学习,并且只能找到一个适用于iOS 9的入门教程。因此,我将从那里开始。 - George B

1

UIUserNotificationSettings 在 iOS 10 中已被 UNNotificationSettings 取代,如果您想要实现 UNNotificationSettings,请按以下方式实现。

首先需要导入 UserNotifications

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge , .sound]) {
     (granted, error) in

}

关于此事的更多细节,请查看 Michał Kałużny 在 UserNotifications.framework 上的 tutorial


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接