【问题标题】:Swift 2.2 compiler forcing Dictionary value to be unwrapped twiceSwift 2.2 编译器强制字典值被解包两次
【发布时间】:2016-03-28 21:24:01
【问题描述】:

在 Swift 2.2 之前,以下代码示例编译成功。使用 2.2 它会导致编译器错误:

// launchOptions: [NSObject: AnyObject]?
if let options = launchOptions {
    if let notifDict = options[UIApplicationLaunchOptionsRemoteNotificationKey] {
        if let phone = notifDict["sender_phone"] {
            let predicate = NSPredicate(format: "phoneNumber == %@", phone)
            // value of optional type 'String?' not unwrapped; did you mean to use...
        }
    }
}

当我已经通过 if let 解包到 Dictionary 值时,为什么会出现此错误?

使用 Xcode 7.3 的注意事项

【问题讨论】:

  • 什么是notifDict
  • @dan - 更新问题

标签: ios swift swift2 optional


【解决方案1】:

您尚未向我们展示您是如何定义 notifDict 的,但请注意,第一个 if let 子句仅检查 "sender_phone" 是否存在值。如果存在这样的值并且如果该值本身是可选的,它不会被解包,只是以其可选形式绑定到predicate

var notifDict : [String: String?] = [:]
notifDict["sender_phone"] = "xxx-xxxxxx"

if let predicate = notifDict["sender_phone"] {
    // predicate is String? here, and needs unwrapping below
    let a = NSPredicate(format: "phoneNumber == %@", predicate ?? "default")
}

这个答案假设notifDict[String: String?] 类型。如果不是(例如,[String: AnyObject] 类型,请参阅@JAL:s answer)。

【讨论】:

    【解决方案2】:

    将字典中的值解包为String

    if let phone = notifDict["sender_phone"] as? String {
        let predicate = NSPredicate(format: "phoneNumber == %@", phone)
        // ...
    }
    

    这是假设 notifDict 的类型为 [String : AnyObject]

    根据更新信息更新答案:

    let launchOptions: [NSObject: AnyObject]? = [UIApplicationLaunchOptionsRemoteNotificationKey: ["sender_phone" : "test"]]
    if let options = launchOptions {
        if let notifDict = options[UIApplicationLaunchOptionsRemoteNotificationKey] {
            if let phone = notifDict["sender_phone"] as? String {
                let predicate = NSPredicate(format: "phoneNumber == %@", phone)
                // ...
            }
        }
    }
    

    【讨论】:

    • 编译器错误“从'字符串向下转换?!' to 'String' 只解开可选项。你的意思是使用 '!!' 吗?"
    • @hgwhittle notifDict 声明为什么?
    • Xcode 7.3 上存在问题。见stackoverflow.com/questions/36171958/…
    • @hgwhittle 抱歉错字,在 Xcode 7.3/iOS 9.3 上测试。
    【解决方案3】:

    自 Xcode 7.3 以来我遇到了同样的问题。就我而言,当我在变量视图中检查userInfo(为您提供notifDict)的类型时,我注意到它是:

    这是AnyObject!,而不是预期的类型[String: String?]

    我所做的是在使用它之前先打开字典:

    guard let myUserInfo = userInfo as? [String:String] else {
        return
    }
    

    这可能与 swift 2.2 无法推断类型属性 https://bugs.swift.org/browse/SR-1024 的这个错误有关,我猜他们以后可能会再次改变行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-03
      • 1970-01-01
      相关资源
      最近更新 更多