paint-brush
Swift Snippet: selectively update object from an optional new valueby@aren.ankit

Swift Snippet: selectively update object from an optional new value

by Ankit AggarwalJanuary 18th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

<a href="https://hackernoon.com/tagged/following" target="_blank">Following</a> operator can be used to update object from new optional value.This can be used when we do not want <a href="https://hackernoon.com/tagged/object" target="_blank">object</a> to get updated to nil from new optional value.
featured image - Swift Snippet: selectively update object from an optional new value
Ankit Aggarwal HackerNoon profile picture

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