Swift2 NotificationType 选项错误

Swift2 NotificationType Option Error

将 Swift 1.2 转换为 Swift 2 后出现错误...不知道如何修复它,smb 在 Swift2 中尝试过吗?

func application(application: UIApplication, 
didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) ->        Bool {

        let notificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
        let settings = UIUserNotificationSettings(forTypes: notificationType, categories: nil)
        application.registerUserNotificationSettings(settings)
        return true
            }

编辑:

Error: "Cannot find initialiser for type 'UIUserNotificationSettings' that accept an argument list of type '(forTypes:[UIUserNotifivati..."

只需从您的代码中更改此部分

let notificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]

进入:

let notificationType: UIUserNotificationType = [.Alert, .Badge, .Sound]

想知道为什么人们不阅读 release notes or documentation (UIUserNotificationType, OptionSetType)。


以下是发行说明摘录:

NS_OPTIONS 类型被导入为符合 OptionSetType 协议,它为选项提供了一个类似集合的接口。 (18069205) 而不是使用按位运算,例如:

// Swift 1.2:
object.invokeMethodWithOptions(.OptionA | .OptionB)
object.invokeMethodWithOptions(nil)
if options & .OptionC == .OptionC {
  // .OptionC is set
}

选项集支持集合字面量语法,以及类似集合的方法,例如contains:

object.invokeMethodWithOptions([.OptionA, .OptionB])
object.invokeMethodWithOptions([])
if options.contains(.OptionC) {
  // .OptionC is set
}

可以在Swift中编写一个新的选项集类型作为符合OptionSetType协议的结构。如果类型指定 rawValue 属性 和选项常量作为 static let 常量,标准库将提供其余选项集的默认实现 API:

struct MyOptions: OptionSetType {
  let rawValue: Int
  static let TuringMachine  = MyOptions(rawValue: 1)
  static let LambdaCalculus = MyOptions(rawValue: 2)
  static let VonNeumann     = MyOptions(rawValue: 4)
}
let churchTuring: MyOptions = [.TuringMachine, .LambdaCalculus]

如@iEmad 所写,只需将一行代码更改为:

let notificationType: UIUserNotificationType = [.Alert, .Badge, .Sound]

你怎么能自己找到这个?错误是...

Error: "Cannot find initialiser for type 'UIUserNotificationSettings' that accept an argument list of type ...

... 这基本上表示您将无效参数传递给初始化程序。什么是正确的论据?同样,文档:

convenience init(forTypes types: UIUserNotificationType,
      categories categories: Set<UIUserNotificationCategory>?)

让我们从最后一个开始 - categories。您正在传递 nil,这没问题,因为 categories 类型是 Set<UIUserNotificationCategory>? = optional = nil 没问题。

所以,问题出在第一个。返回文档,我们可以在其中找到 UIUserNotificationType 声明:

struct UIUserNotificationType : OptionSetType {
    init(rawValue rawValue: UInt)
    static var None: UIUserNotificationType { get }
    static var Badge: UIUserNotificationType { get }
    static var Sound: UIUserNotificationType { get }
    static var Alert: UIUserNotificationType { get }
}

嗯,采用OptionSetType。在 Swift 1.2 中没有看到这个,它一定是新的东西。让我们打开 documentation 并了解更多信息。啊,有趣,很好,我必须调整我的代码。

请开始阅读发行说明和文档。您将节省一些时间。