Perform assignment only if right side is not nil

There are various ways that aren't too unwieldy

Using ?? :

object.nonOptionalProperty = funcThatReturnsOptional() ?? object.nonOptionalProperty 

Using a function :

func setNotNil<T>(inout variable:T, _ value:T?)
{ if value != nil { variable = value! } }

setNotNil(&object.nonOptionalProperty, funcThatReturnsOptional())

Using an operator :

infix operator <-?? { associativity right precedence 90 assignment }
func <-??<T>(inout variable:T, value:T?)
{ if value != nil { variable = value! } }

object.nonOptionalProperty <-?? funcThatReturnsOptional() 

Using an extension :

extension Equatable
{ mutating func setNotNil(value:Self?) { if value != nil { self = value! } } }

object.nonOptionalProperty.setNotNil(funcThatReturnsOptional())

A single expression with the same effect as your code is

funcThatReturnsOptional().map { object.nonOptionalProperty = $0 }

but your code is definitely better readable.

Here the map() method of Optional is used and the closure is executed only if the function does not return nil.

Tags:

Swift