Swift does not assign variables from JSON results

I have a problem loading JSON results into swift (php connection).

I can get JSON data, but that won't let me assign it to a variable.

it always assigns the results as Optional

.

JSON data:

{
"country": [{
    "id": 1,
    "name": "Australia",
    "code": 61
}, {
    "id": 2,
    "name": "New Zealand",
    "code": 64
}]
}

      

XCode output:

 ["country": <__NSArrayI 0x60000002da20>(
 {
     code = 61;
     id = 1;
     name = Australia;
 },
 {
     code = 64;
     id = 2;
     name = "New Zealand";
 }
 )
 ]
 Country Name: Optional(Australia)
 Country Name: Optional(New Zealand)

      

Swift file:

//function did_load
override func viewDidLoad() {
    super.viewDidLoad()

    //created RequestURL
    let requestURL = URL(string: get_codes)

    //creating NSMutable
    let request = NSMutableURLRequest(url: requestURL!)

    //setting the method to GET
    request.httpMethod = "GET"

    //create a task to get results
    let task = URLSession.shared.dataTask(with: request as URLRequest) {
        data, response, error in

        if error != nil{
            print("error is \(String(describing: error))")
            return;
        }

        //lets parse the response
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: Any]
            print(json)
            if let countries = json["country"] as? [[String: AnyObject]] {
                for country in countries {
                    print("Country Name: \(String(describing: country["name"]))")
                    print("Country Code: \(String(describing: country["code"]))")
                    if let couname = country["name"] as? [AnyObject] {
                        print(couname)
                    }

                    if let coucode = country["code"] as? [AnyObject] {
                        print(coucode)
                    }
                }
            }
        } catch {
            print("Error Serializing JSON: \(error)")
        }
    }
    //executing the task
    task.resume()
}

      

+3


source to share


1 answer


You need to expand the option before trying to use it using string interpolation. The safest way to do this is through optional binding:

Please use below code that will work for you.



  if let countries = json["country"] as? [[String: AnyObject]] {
            for country in countries {
                print("Country Name: \(country["name"] as! String)")
                print("Country Code: \(country["code"] as! String)")
                if let couname = country["name"] as? String {
                    print(couname)
                }

                if let coucode = country["code"] as? Int {
                    print(coucode)
                }
            }
        }

      

+3


source







All Articles