I have a JSON file called points.json, and a read function like:
private func readJson() {
let file = Bundle.main.path(forResource: "points", ofType: "json")
let data = try? Data(contentsOf: URL(fileURLWithPath: file!))
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
print(jsonData)
}
It does not work, any help?
The Swift 4.2 / iOS 12 code below shows a possible rewrite of your method that avoids force unwrap on optional values and handles gently potential errors:
Your problem here is that you force unwrap the values and in case of an error you can't know where it comes from.
Instead, you should handle errors and safely unwrap your optionals.
And as @vadian rightly notes in his comment, you should use
Bundle.main.url
.When coding in Swift, usually,
!
is a code smell. Of course there's exceptions (IBOutlets and others) but try to not use force unwrapping with!
yourself and always unwrap safely instead.