Blog

Functional Snippet #19: Replacing a Complicated API With Optionals

Sometimes it’s nice to make lightweight API wrappers as top-level functions, or completely wrap an API as described in the sample chapter of Functional Programming in Swift. In this snippet, we will instead add an extension to NSScanner.

If we consider NSScanner, the API feels a bit off in Swift. For example, to scan an Int value, we need to call the following method:

func scanInteger(result: UnsafeMutablePointer<Int>) -> Bool

In Objective-C, this API made sense (pass in a pointer to an integer, which you should only read out if the function returns YES). In Swift, this can be solved in a much nicer way using optionals, by wrapping the original method:

extension NSScanner {
    func scanInteger() -> Int? {
        var result: Int = 0
        return scanInteger(&result) ? result : nil
    }
}

Just looking at the type, this is way simpler. The function will either return an integer or not. There’s no need to look at the documentation to see how the UnsafeMutablePointer and the Bool interact.

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

Back to the Blog

recent posts