Oscar Cooke-Abbott Oscar Cooke-Abbott - 1 month ago 14
Swift Question

Swift 3 Compiler Errors with JSON and Dictionaries within URLSession.shared.dataTask

After previous issues with this particular app code as 'solved' with help, a new issue has arisen with this code:

var properties: [String] = []
var unsortedDetails: [String] = []
var contacts: [[String]] = []
var propertySorting: [(key: String, ind: String, link: Bool)] = []
var autolinks: [Bool] = []


and, in the viewDidLoad function:

let contactsRequest = URLRequest(url: URL(string: "https://script.google.com/macros/s/AKfycbxOLElujQcy1-ZUer1KgEvK16gkTLUqYftApjNCM_IRTL3HSuDk/exec?id=" + ID + "&sheet=" + Industry.replacingOccurrences(of: " ", with: "+", options: NSString.CompareOptions.literal, range: nil))!)

let contactsTask = URLSession.shared.dataTask(with: contactsRequest as URLRequest)
{(data, response, error) in
do {
let jsonResult: Dictionary = try JSONSerialization.jsonObject(with: data!, options: []) as! [String : Any]

let results = jsonResult[self.Industry] as! [[String : Any]]

for key in results[0].keys {
self.propertySorting.append(key: (key as? String)!, ind: results[0].value(forKey: key as! String) as! String, link: results[1].value(forKey: key as! String) as! String != "X")
}
self.propertySorting.sort(by: {Int($0.ind) < Int($1.ind)})

for property in self.propertySorting {
self.properties.append(property.key)
self.autolinks.append(property.link)
}

for contact in results {
self.contacts.append([])
for key in self.properties {
self.contacts[self.contacts.count-1].append(contact.value(forKey: key) as! String)
}
}

DispatchQueue.main.async(execute: {
let listController = self.viewControllers[0] as! ListController

listController.properties = self.properties
listController.contacts = self.contacts
listController.autolinks = self.autolinks

listController.tableView.reloadData()
})

} catch {
print("FATAL ERROR")
}
}

contactsTask.resume()


The issues now encountered are:
Extra argument 'ind' in call
when propertySorting.append(...) is called, and if this (previously working)
ind
section is deleted, the same error is returned for
link

Answer

Instead of NSArray and NSDictionary used Swift native Array and Dictionary and use keys with Dictionary to get array of all keys.

let jsonResult: Dictionary = try JSONSerialization.jsonObject(with: data!, options: []) as! [String : Any]
let results = jsonResult[self.Industry] as! [[String : Any]]

for key in results[0].keys {

}

Note: There is no need to use .mutableContainers option with Swift native type object.

Comments