Find and Replace with JSON and Aldwych in Swift


Find and Replace

In the ongoing series of posts on parsing JSON with Aldwych in Swift, I want to consider some newly added find and replace functionality and to think of some scenarios where it might be useful. For example, let's suppose we want to Americanize the string content of JSON coming from a UK source. Here this is demonstrated with a small subset of Americanisms.
import UIKit

let spellingsUS = ["aeroplane":"airplane","aluminium":"aluminum","arse":"ass","behove":"behoove","bogeyman":"boogeyman","brent":"brant","carburettor":"carburetor","coupé":"coupe"]

let article:[String:AnyObject] = ["a":["I was on an aluminium aeroplane"],"b":"unafraid","c":[["c":"of the bogeyman","d":"when he ripped the carburettor off my coupé"],"what an arse!"]]


var dict = JSONDictionary(dict: article)

for (k,v) in spellingsUS {
    replaceStringWithStringInJSONDictionary(k, &dict, v)
}

var myError:NSError?
if let jString = dict.stringify(options: nil, error: &myError) {
    println(jString) // "{"b":"unafraid","a":["I was on an aluminum airplane"],"c":[{"d":"when he ripped the carburetor off my coupe","c":"of the boogeyman"},"what an ass!"]}"
}
To experiment with this code in the latest beta of Xcode 6.3, simply create a playground, press Command + 1 and drag the files from the Aldwych "Sources" folder into the "Sources" folder of the playground. Next copy and paste the above code into the main playground file.

One more time with GREP

To extend the find and replace functionality it is also possible to use regular expressions. For example:
import UIKit

let pointsToBeMade:[String:AnyObject] = ["a":"This is my first assertion - point 1", "b":["And here's another idea - point 2",["c":"And of course a third - point 3"]]]

var dict = JSONDictionary(dict: pointsToBeMade)

replaceStringUsingRegularExpressionInJSONDictionary("(.*)( - point) ([0-9])", &dict, withString:"$3. $1")

var myError:NSError?
if let jString = dict.stringify(options: nil, error: &myError) {
    println(jString) // "{"b":["2. And here's another idea",{"c":"3. And of course a third"}],"a":"1. This is my first assertion"}"
}

Back to Data

By creating the ability to manipulate JSON without first transforming it into another type means that it is also easy to transform the JSON back to data by simply doing this:
var error:NSError?
if let d = dict.jsonData() {
    d // data
}

Conclusion

This is the very beginning of some features that are being added to Aldwych and there are plenty more ideas being worked on. I hope that you'll keep an eye on the repository, contribute ideas and help to expand JSON handling in Swift into something exciting and useful. I'm certainly enthused by all that has been achieved so far and cannot thank people on twitter enough who RT and share my enthusiasm.


Endorse on Coderwall

Comments