Read JSON file with Swift 3

前端 未结 2 560
余生分开走
余生分开走 2020-12-13 13:15

I have a JSON file called points.json, and a read function like:

private func readJson() {
    let file = Bundle.main.path(forResource: \"points\",          


        
2条回答
  •  一整个雨季
    2020-12-13 13:19

    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.

    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.

提交回复
热议问题