Here's a quick extension for [String: AnyObject]
dictionaries in Swift. The output needs to be in the following format (order and spacing don't matter):
{"key": "val", "keywdict": {"anotherKey": 100, "Key2": "Val2"}, "strings": ["string", "another"]}
I am wondering if there's a better way, or if this can be improved.
extension Dictionary //...
func toJSONString() -> String {
var pcs = [String]()
for (key, val) in self {
var valStr = ""
if let val = val as? String {
valStr = "\"\(val)\""
} else if let val = val as? Dictionary<String, AnyObject> {
valStr = val.toJSONString() // recursion for nested dictionaries
} else if let val = val as? Array<String> {
let tmpStr = "\",\"".join(val)
valStr = "[\"\(tmpStr)\"]"
} else if let val = val as? NSNumber {
valStr = "\(val)"
}
pcs.append("\"\(key)\":\(valStr)")
}
return "{" + ",".join(pcs) + "}"
}