Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift 2.2编译器强制字典值展开两次_Ios_Swift_Swift2_Optional - Fatal编程技术网

Ios Swift 2.2编译器强制字典值展开两次

Ios Swift 2.2编译器强制字典值展开两次,ios,swift,swift2,optional,Ios,Swift,Swift2,Optional,在Swift 2.2之前,以下代码示例已成功编译。对于2.2,它给出编译器错误: // launchOptions: [NSObject: AnyObject]? if let options = launchOptions { if let notifDict = options[UIApplicationLaunchOptionsRemoteNotificationKey] { if let phone = notifDict["sender_phone"] {

在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...
        }
    }
}
如果let,当我已经通过
展开到字典值时,为什么会出现此错误


注意:使用Xcode 7.3将字典中的值作为字符串展开:

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)
            // ...
        }
    }
}

您没有向我们展示如何定义
notifDict
,但请注意,第一个
if let
子句只是检查键
“sender\u phone”
是否存在值。如果存在这样一个值,并且该值本身是可选的,则不会将其展开,只需将其以可选形式绑定到
谓词

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]
,请参阅)。

自Xcode 7.3以来,我遇到了相同的问题。在我的例子中,当我检查变量视图中的
userInfo
notifDict
)类型时,我注意到它是:

这是
AnyObject而不是预期的类型
[字符串:字符串?]

我所做的是在使用之前先打开DICITORY:

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

这可能与swift 2.2无法推断类型属性的错误有关,我猜他们以后可能会再次改变行为

什么是
notifDict
?@dan-更新的问题编译器错误“从'String?!'向下转换为'String'仅打开选项。您的意思是使用'!!'?“@hgwhittle什么是
notifDict
声明的?Xcode 7.3上存在问题。请参阅@hgwhittle抱歉的打字错误,在Xcode 7.3/iOS 9.3上测试。