1

I am writing a Swift application that relies in part on a large dictionary of arrays. An excerpt looks like this:

let arithmeticalDict:Dictionary<String, Array <String>> =
[
    "1116": [],
    "1117": [],
    "1118": ["(1+1+1)*8"],
    "1128": ["1*(1 + 2)*8","(1 + 2)/(1/8)"]
]

I think it might be more manageable to put this into a JSON resource, a technique I have used before for small, simple dictionaries. This case is larger, 715 entries that take up some 370Kb on disk. However in this case I have run into two problems:

  1. How do I specify in the JSON file that each key in the dictionary corresponds to an array of strings (where the arrays are of irregular length and some may contain nothing)?

  2. How do I extract the JSON file into an appropriate <String, Array <String>> dictionary when loading it in Swift?

1 Answer 1

2

1- Your dictionary is already typed, it's Dictionary<String, Array <String>>, so you just have to use NSJSONSerialization to create the JSON data:

do {
    let jsonData = try NSJSONSerialization.dataWithJSONObject(arithmeticalDict, options: NSJSONWritingOptions.PrettyPrinted)
    // now you can export "jsonData" to a file
} catch {
    print(error)
}

2- To decode the saved JSON object just use the same type again:

do {
    if let dict = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as? [String:[String]] {
        print(dict)  // ["1118": ["(1+1+1)*8"], "1117": [], "1116": [], "1128": ["1*(1 + 2)*8", "(1 + 2)/(1/8)"]]
    }
} catch {
    print(error)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.