Monday, November 2, 2015

If-Let Assignment Operator

Weston Hanners defines a custom Swift operator (via This Week in Swift):

infix operator ?= { associativity right precedence 90 }

func ?=<T>(inout left: T, right: T?) {
    if let value = right {
        left = value
    }
}

func ?=<T>(inout left: T?, right: T?) {
    if let value = right {
        left = value
    }
}

So that code like:

if let value = someOptionalValue as? String {
  self.value = value
}

Can be written as:

self.value ?= someOptionalValue as? String

I like the brevity, but often I care that there was no value, or perhaps want to report why there wasn’t one (e.g. which key was missing). So I kind of see this as a way to make the compiler happy, which is not necessarily the same thing as properly handling the unexpected situation. I might prefer a pattern where the helper extracts the value from the containing object, rather than checking it after the fact.

Comments RSS · Twitter

Leave a Comment