有没有更好的方法来检查活动通知设置?

Is there a better way to check active notification settings?

在 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)")
}

看来您唯一可以改进代码的方法就是让它更简洁。

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 的 swift 映射。在 Xcode 的早期测试版中,这些对象还实现了 BooleanType,这可以让您将此代码编写得更简洁一些,但似乎在发布之前已被删除。

另外,四处搜索,最常见的检查方式是!= nil所以我也包含了那个修改,它似乎提高了一点可读性。

这是一个非常强大的 Whosebug post 主题:Switch statement for imported NS_OPTIONS (RawOptionSetType) in Swift?

还有另一篇关于 RawOptionSetType 背景的精彩文章:http://nshipster.com/rawoptionsettype/