可选类型“AnyObject?”的值没打开你的意思是用!或

时间:2015-10-24 22:06:29

标签: ios objective-c swift

我从服务器收到JSON响应。

 do {
    let response = try NSJSONSerialization.JSONObjectWithData(data!,options:NSJSONReadinOptions.AllowFragments)
    let cityDetails  = reponse["cityDetails"]

    if cityDetails!.isKindOfClass(NSArray) {

    }
 }catch {
   println("Error \(error)")
 }

我收到以下消息

Value of optional Type "AnyObject?" not unwrapped did you mean to use ! or ??

我后来添加的修正是使用双!!如果cityDetails!!.isKindOfClass(NSArray)

下面列出了两个要理解的问题?

1)为什么要重新取消对象,即使它已经被包裹了一次。

2)以下代码执行相同的操作,但只需要解包一次。此外,它崩溃,因为结果碰巧是nil.In Objectice C,nil已经处理并且在这种情况下将返回false,而不是崩溃应用程序。在那个声明中。

let testDictionary:[String:AnyObject] = ["a",NSMutableArray()]
let result = testDictionary["C"]

if result.isKindOfClass(NSArray) {

}

输入后的答案 2)为了解决第二个问题,我使用以下代码。

方法1

if let _ = result {

    if result.isKindOfClass(NSArray) {

    }
}

方法2

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    let testDictionary:[String:AnyObject] = ["a":NSMutableArray()]

    let result = testDictionary["C"]

    print("Before details Check")
    guard let details = result where details.isKindOfClass(NSArray) else {
        return false
    }
    print("Returned Result \(details)")
    print("After Details Check")
    return true
}

1 个答案:

答案 0 :(得分:0)

通过解包值,如果让保护让语句:

guard let cityDetails = response["cityDetails"] as? NSArray else {
    // Something went wrong trying to turn response["cityDetails"] into an unwrapped NSArray
    return
}

// From this point cityDetails will be an unwrapped NSArray

强制解包变量是你应该尽可能避免的事情。

另一个片段:

 guard let result = result  // Unwrap result
    where result.isKindOfClass(NSArray) else { // Ask the unwrapped value if it's an NSArray
    return // If one of above is not the case we shouldn't continue
}