0

this is my first time at swiftlyJSON and I have a problem. I have data in the local json file and I need to take a single object with this file. I used swiftlyjson but I don't know how to parse a file. Now I have an idea to convert the file to a string and this string goes to JSON. I have something like that, thats work, but I'm looking for the easiest way

import Foundation
class TakeDataPropertiesDish{

    func parseData(){
        var json: String = ""
        if let filepath = Bundle.main.path(forResource: "PropertiesDish", ofType: "json") {
            do {
                json = try String(contentsOfFile: filepath)
            } catch {
                print("error parse json file to string")
            }
        }

        if let data = json.data(using: .utf8) {
            if let json = try? JSON(data: data) {
                for item in json["dish"].arrayValue {
                    print(item["name"].stringValue)
                }
            }
        }
    }
}
Triker
  • 11
  • 4
  • Please have a look at this answer https://stackoverflow.com/a/24411014/3266248 – mihatel Dec 05 '19 at 20:24
  • thanks, its works, but function looks worse and harder than in my idea, how do you think which way is better? – Triker Dec 05 '19 at 21:04

1 Answers1

1

If you want to eliminate nested 'if let' statements then you can use guard statement:

func parseData() {
    guard let filepath = Bundle.main.path(forResource: "PropertiesDish", ofType: "json") else { return }
    guard let jsonData: Data = try? String(contentsOfFile: filepath).data(using: .utf8) else { return }
    guard let json = try? JSON(data: jsonData) else { return }
    for item in json["dish"].arrayValue {
        print(item["name"].stringValue)
    }
}
Maciej Chrzastek
  • 1,380
  • 12
  • 18