如何从 Swift 中的 error.userInfo 获取 ["error"]["type"]?

How to get ["error"]["type"] from error.userInfo in Swift?

我想知道我们如何在 Swift 中做到这一点?

我正在尝试将下面的代码转换为 Swift

FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:nil];
    [request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
        if (!error) {
            // handle successful response
        } else if ([[error userInfo][@"error"][@"type"] isEqualToString: @"OAuthException"]) { // Since the request failed, we can 
            NSLog(@"The facebook session error");
        } else {
            NSLog(@"Some other error: %@", error);
        }
    }];

这是我所做的。

request.startWithCompletionHandler { (connection: FBSDKGraphRequestConnection!, result: AnyObject!, error: NSError!) -> Void in
        if error == nil {
            // handle successful response
        }
        else if error.userInfo["error"]["type"] == "OAuthException" { 
           //THIS LINE WONT COMPILE

        }
        else {
            println("Some other error");
        }
    }

但是我得到一个编译错误,在这一行 could not find member 'subscript'

error.userInfo["error"]["type"] == "OAuthException" 

有什么想法吗?

尝试:

if (error.userInfo?["error"]?["type"] as? String) == "OAuthException" {

userInfo[NSObject: AnyObject]? 类型的可选字典,因此您需要将其解包。字典查找总是 return 一个可选的(因为键可能不存在)所以你必须在访问嵌套字典的键之前打开它。使用 ? 而不是 ! 可选链接 如果 "error" 键不存在,它将无害地导致 nil (如果你使用 ! 而不是崩溃)。最后,您需要将结果转换为 String(来自 AnyObject),以便能够将其与 "OAuthException".

进行比较

如何分解错误并键入如下所示?

           else if let errorOAuthException: AnyObject =  error.userInfo as? Dictionary<String, AnyObject>{

            if errorOAuthException["error"] != nil {
                if errorOAuthException["type"] as? String == "OAuthException" {

                //Do something for me
                }
            }


        }