Swift Snippet: selectively update object from an optional new value

Written by aren.ankit | Published 2017/01/18
Tech Story Tags: swift | ios-app-development | mobile-app-development | ios | swift-programming

TLDRvia the TL;DR App

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


Published by HackerNoon on 2017/01/18