这里的问题是,您强制展开值,如果出现错误,您无法知道它来自何处.
相反,你应该处理错误并安全地打开你的选项.
正如@vadian在他的 comments 中正确指出的,你应该使用Bundle.main.url
.
private func readJson() {
do {
if let file = Bundle.main.url(forResource: "points", withExtension: "json") {
let data = try Data(contentsOf: file)
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let object = json as? [String: Any] {
// json is a dictionary
print(object)
} else if let object = json as? [Any] {
// json is an array
print(object)
} else {
print("JSON is invalid")
}
} else {
print("no file")
}
} catch {
print(error.localizedDescription)
}
}
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.