Earlier today I was writing some code that looked like this:

if let foo = bar.foo {
    fooLabel.text = foo
} else {
    fooLabel.text = ""
}
if let baz = bar.baz {
    bazLabel.text = baz
} else {
    bazLabel.text = ""
}

I figured there had to be a cleaner way to express this. My initial thought process was to write an extension to String that does this. Very quickly though, I realized I need to extend Optional, not String.

So I came up with this:

extension Optional {
    public func or(other: Wrapped) -> Wrapped {
        if let ret = self {
            return ret
        } else {
            return other
        }
    }
}

This allows me to now write:

fooLabel.text = bar.foo.or(other: "")

Much better!

Then I thought, there’s a way to make this even better for Optional<String> specifically. So I came up with this:

extension Optional where Wrapped == String {
    public func orEmpty() -> String {
        return self.or(other: "")
    }
}

And voila! I can now write:

fooLabel.text = bar.foo.orEmpty()

Way better!

Gopal Sharma

gps gopalkri


Published