2

将 Swift1.2 突变为 Swift2 后出现错误...不知道如何修复它,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
            }

编辑:

错误:“找不到接受类型参数列表的“UIUserNotificationSettings”类型的初始化程序“(forTypes:[UIUserNotifivati ...”

4

2 回答 2

4

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

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

进入:

let notificationType: UIUserNotificationType = [.Alert, .Badge, .Sound]
于 2015-06-13T17:32:26.477 回答
2

想知道为什么人们不阅读发行说明或文档(UIUserNotificationTypeOptionSetType)。


以下是发行说明摘录:

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]

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

错误:“找不到接受类型参数列表的“UIUserNotificationSettings”类型的初始化程序......

...这基本上说您将无效参数传递给初始化程序。什么是正确的论点?再次,文档:

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

让我们从最后一个开始 - categories。你通过nil了,这没关系,因为categoriestype is 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 中没有看到这个,它一定是新的东西。让我们打开文档并了解更多信息。啊,有趣,很好,我必须调整我的代码。

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

于 2015-07-06T22:13:45.157 回答