getOrElse in Swift’s Optional

Now I couldn’t resist throwing my own two cents onto buzz around Swift  language. Right now, we are on early stage of excitement, which means lots of tutorials, and emerging libraries and extensions, including a few ones which sometimes recreate features that already exist :)

But to the point.

One of respectable Swift features are optionals. They are more important than many of you may think, so it is good to take closer look.

Optionals are wrapping value which may or may not be present. Consider an example: we have string which we want to convert to a number:

var maybeANumber = "456"
var asNumber = maybeANumber.toInt()

When typed in Playground, asNumber value is {Some 456}. If you really want a number, you need to unwrap it

asNumber!

Forced unwrap operator, exclamation mark, will, however generate an error when input value is not a string. Eventually you end up with if-checking:

if let actual = asNumber {
     actual
 } else {
     0
 }

Optional type implements LogicValue protocol, so any Optional variable can be used in conditional expression.

This is not satisfactory for me, though. If language is borrowing so many good parts from functional language like Scala, why not steal more? Scala’s Option type offers a number of methods, including getOrElse(default), which returns a wrapped value if it exists, or provided default otherwise.

There’s no such thing in Swift (yet). So that encouraged me to implement it by myself. Swift documentation is very high-level, with little to none specific of under-the-hood operation.

After fiddling with undocumented methods a came to my own implementation of .getOrElse() using extension:

extension Optional {
    func getOrElse(val:T) -> T  {
        if getLogicValue() {
            return self!
        } else {
            return val
        }
    }
}

You can find in in my GitHub gist. Now, instead of creating if on the very end of chained Optional calls, use nice and clean:

"123".toInt().getOrElse(0// 123
"foo".toInt().getOrElse(0// 0

I really hope to find such feature in Swift 1.1, otherwise it is a good start of functional extensions library for Swift.

Reboot

This is unintentional reboot of blog and website. It used to be hosted on friends server provided to me as a courtesy. It ran there for years, and suddenly stopped functioning.

The friends server has been sunset, and he forgot to notify me. Looks like I was extremely trouble-free tenant.

It is a good opportunity to start from scratch, possibly revive some posts from archives.