I just recently started working at Swift and I still don’t understand much

I wrote this code

if let myData = data{ do{ let myJson = try JSONSerialization.jsonObject(with: myData, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject if let data = myJson["data"] as AnyObject? { let id = data["id"] as! NSString? print (id!) let logo = data["logo"] as! NSString? print (logo!) let name = data["name"] as! NSString? print (name!) } let status = myJson["status"] as! String! print (status!) if(status == "OK") { UserDefaults.standard.set(true,forKey:"isUserLoggedIn"); UserDefaults.standard.synchronize(); self.dismiss(animated: true, completion: nil); } } 

when the login and password are correct, everything is fine my JSON code comes and I can parse it, but if the login or password is incorrect, then the program knocks out and issues an error fatal error

I check the login and password on the server

  • Perhaps you are trying to get a key that does not exist. When an error arrives, what does JSON look like? - Vitali Eller

2 answers 2

Obviously that falls on some of the ! . Either rewrite in order to eliminate the possibility that where you are doing force unwrap will skip nil, or use SwiftyJSON . With its help you can easily and safely parse JSON.

    instead of this code

     let id = data["id"] as! NSString? print (id!) let logo = data["logo"] as! NSString? print (logo!) let name = data["name"] as! NSString? print (name!) } let status = myJson["status"] as! String! print (status!) 

    try the following

     if let id = data["id"] as? String { print (id) } if let logo = data["logo"] as String { print (logo) } if let name = data["name"] as? String { print (name) } 

    In this case, you will enter the condition body only if you have a value under these keys and this value has the String data type.

    • so I tried to vseravno crashes on the ideas you need to add some kind of else myJson == nil {return} but for some reason it does not work - Sergey