A simple way to achieve that is to just extend CollectionType.
Use optional binding and downcasting, then serialize to data, then convert to string.
extension CollectionType where Generator.Element == [String:AnyObject] {
func toJSONString(options: NSJSONWritingOptions = .PrettyPrinted) -> String {
if let arr = self as? [[String:AnyObject]],
let dat = try? NSJSONSerialization.dataWithJSONObject(arr, options: options),
let str = String(data: dat, encoding: NSUTF8StringEncoding) {
return str
}
return "[]"
}
}
let arrayOfDictionaries: [[String:AnyObject]] = [
["abc":123, "def": "ggg", "xyz": true],
["abc":456, "def": "hhh", "xyz": false]
]
print(arrayOfDictionaries.toJSONString())
Output:
[
{
"abc" : 123,
"def" : "ggg",
"xyz" : true
},
{
"abc" : 456,
"def" : "hhh",
"xyz" : false
}
]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…