Blog

Functional Snippet #11: Lightweight API Wrappers

Objective-C APIs are inherently less type safe than what we’d like to have when writing Swift code. Take for example Foundation’s JSON serialization API +JSONObjectWithData:options:error:. This class method returns an object of type AnyObject?. If we know though that we’re always expecting a dictionary, then we can make our lives easier by introducing a small wrapper function:

typealias JSONDictionary = [String:AnyObject]

func decodeJSON(data: NSData) -> JSONDictionary? {
    return NSJSONSerialization.JSONObjectWithData(data, 
        options: .allZeros, error: nil) as? JSONDictionary
}

This saves us the optional cast to a dictionary type every time we use this function. Additionally, the expectation to receive dictionaries from the server is explicit in the type signature of the function.

Of course we can do the same for JSON encoding as well:

func encodeJSON(input: JSONDictionary) -> NSData? {
    return NSJSONSerialization.dataWithJSONObject(input, 
        options: .allZeros, error: nil)
}

We could even go one step further and return a result value that has the potential error embedded instead of a simple dictionary.

The bottom line is: Swift makes it very easy to define such wrapper functions to make our application code more clear and simple. Use them liberally.

Stay up-to-date with our newsletter or follow us on Twitter.

Back to the Blog

recent posts