1
\$\begingroup\$

For a small system I need the Country Code mapped to the country name (e.g. "GB"-> "United Kingdom"). To accomplish that I read a JSON file and save it to a dictionary using swiftyJSON. Is there a cleaner and better way than I did:

fileprivate func loadNames() {
    if let filePath = Bundle.main.path(forResource: "countryNames", ofType: "json") {
        if let jsonData = NSData(contentsOfFile: filePath) {
            let json = JSON(jsonData)
            countryNames = json.dictionaryObject! as NSDictionary
        }
    }
}

The JSON looks like this:

{
"BD": "Bangladesh", 
"BE": "Belgium",
...
}
\$\endgroup\$
2
\$\begingroup\$

There's nothing wrong with what you currently have. However, a plist is another option, if this JSON is just static file.

The nice thing about the property list format is that Xcode has built-in support for editing it and Foundation has built-in support for reading it.

fileprivate func loadNames() {
    if let filePath = Bundle.main.path(forResource: "countryNames", ofType: "plist") {
        countryNames = NSDictionary(contentsOfFile: filePath)!
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.