在 Swift 中是否有更好的方法来检查是否在 application.currentUserNotificationSettings().types
上设置了特定标志?
例如,您将如何检查应用程序是否允许更新它的角标(Badge)?
下面是我当前使用的方法,但我认为 Swift 中可能有更好的方法,比如一些我不知道的运算符。
func printUserNotificationSettings() {
println("Notification Settings:")
let notificationSettingsTypes = UIApplication.sharedApplication().currentUserNotificationSettings().types
let badgeOn: Bool = (notificationSettingsTypes & UIUserNotificationType.Badge) == UIUserNotificationType.Badge
let soundOn: Bool = (notificationSettingsTypes & UIUserNotificationType.Sound) == UIUserNotificationType.Sound
let alertOn: Bool = (notificationSettingsTypes & UIUserNotificationType.Alert) == UIUserNotificationType.Alert
println("\tBadge? \(badgeOn)")
println("\tSound? \(soundOn)")
println("\tAlert? \(alertOn)")
}
最佳答案
看来要改进代码,唯一可以做的就是使其更加简洁。
func printUserNotificationSettings() {
println("Notification Settings:")
let notificationSettingsTypes = UIApplication.sharedApplication().currentUserNotificationSettings().types
let badgeOn = (notificationSettingsTypes & .Badge) != nil
let soundOn = (notificationSettingsTypes & .Sound) != nil
let alertOn = (notificationSettingsTypes & .Alert) != nil
println("\tBadge? \(badgeOn)")
println("\tSound? \(soundOn)")
println("\tAlert? \(alertOn)")
}
UIUserNotificationType
实现了 RawOptionSetType
,它是 Objective C 代码中 NS_OPTIONS
的快速映射。在早期的 Xcode 测试版中,这些对象还实现了 BooleanType
,这会让您可以更简洁地编写此代码,但似乎在发布之前已将其删除。
另外,四处搜索,最常见的检查方法是 != nil
所以我也包含了那个修改,它似乎提高了一点可读性。
这里有一篇关于该主题的非常强大的 StackOverflow 帖子:Switch statement for imported NS_OPTIONS (RawOptionSetType) in Swift?
还有另一篇关于 RawOptionSetType 背景的精彩文章:http://nshipster.com/rawoptionsettype/
关于ios - 有没有更好的方法来检查事件通知设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30108395/