Before you go, check out these stories!

0
Hackernoon logoSwift Snippet: selectively update object from an optional new value by@aren.ankit

Swift Snippet: selectively update object from an optional new value

Author profile picture

@aren.ankitAnkit Aggarwal

Following operator can be used to update object from new optional value.This can be used when we do not want object to get updated to nil from new optional value.

Frequently used when mapping server response since we do not get all params in every response and by using this operator we do not have to check for all non optionals value again and again.

infix operator ?= : MultiplicationPrecedence
func ?= <T> ( property: inout T?, newValue: T?) {
   if let value = newValue {
      property = value
   }
}
func ?= <T> ( property: inout T, newValue: T?) {
   if let value = newValue {
       property = value
   }
}
Usage
var name: String? = nil
screenName ?= name

Tags

The Noonification banner

Subscribe to get your daily round-up of top tech stories!