条件绑定的初始化程序必须具有可选类型,而不是' NSDictionary'

时间:2015-10-10 22:14:23

标签: ios json swift swift2 ios9

我不知道我需要一个可选类型意味着什么。我试图做Do / catch,但它似乎仍然没有效果。

do {
    let json = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as! NSDictionary

    if let parseJSON = json {

        let userId = parseJSON["userId"] as? String
        if (userId != nil) {

            NSUserDefaults.standardUserDefaults().setObject(parseJSON["userFirstName"], forKey: "userFirstName")
            NSUserDefaults.standardUserDefaults().setObject(parseJSON["userLastName"], forKey: "userLastName")
            NSUserDefaults.standardUserDefaults().setObject(parseJSON["userId"], forKey: "userId")
            NSUserDefaults.standardUserDefaults().synchronize()

            // take user to a protected page
            /*
            let mainPage = self.storyboard?.instantiateViewControllerWithIdentifier("MainPageViewController") as! MainPageViewController

            let mainPageNav = UINavigationController(rootViewController: mainPage)
            let appDelegate = UIApplication.sharedApplication().delegate

            appDelegate?.window??.rootViewController = mainPageNav
            */

            let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

            appDelegate.buildNavigationDrawer()

        } else {

            // display an alert message
            let userMessage = parseJSON["message"] as? String
            let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert);
            let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:nil)
            myAlert.addAction(okAction);
            self.presentViewController(myAlert, animated: true, completion: nil)
        }

    }
} catch {
   print(error)
}

1 个答案:

答案 0 :(得分:0)

使用此行,使用as!

let json = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as! NSDictionary

强制将NSJSONSerialization的结果强制转换为NSDictionary。

因此生成的json不是可选的:您不必用if let打开它。

删除if let parseJSON = json { }部分并直接使用json

let userId = json["userId"] as? String

或者,如果您想将结果保持为可选,则可以使用as?

if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as? NSDictionary {
    let userId = json["userId"] as? String
    // etc
}