Swift中是否有更好的方法来检查application.currentUserNotificationSettings().types
上是否设置了特定标志?
例如,您如何检查应用程序是否允许更新徽章?
以下是我目前正在使用的方法,但我认为在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)")
}
答案 0 :(得分:1)
看起来你可以做的唯一改进代码就是让它更简洁。
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/