Skip to content

Instantly share code, notes, and snippets.

@jpmcglone
Created October 4, 2016 16:56
Show Gist options
  • Save jpmcglone/f1c1e32023832254f5303b8fd46afc4b to your computer and use it in GitHub Desktop.
Save jpmcglone/f1c1e32023832254f5303b8fd46afc4b to your computer and use it in GitHub Desktop.
Swift 3 - Set if not nil
import Foundation
func setIfNotNil<T>(_ obj: inout T?, _ other: T?) {
guard other != nil else { return }
obj = other
}
@seivan
Copy link

seivan commented Oct 4, 2016

var sample:Int? = 3
var sampleEmpty:Int? = nil
var sampleNotEmpty:Int? = 100

func setIfNotNil<T>(_ obj: inout T?, _ other: T?) {
    guard other != nil else { return }
    obj = other
}

func testCaseOne(lhs:Int?, rhs:Int?) {
    var l = lhs
    setIfNotNil(&l, rhs)

}


func testCaseTwo(lhs:Int?, rhs:Int?) {
    var l = lhs
    l = rhs ?? l
}


testCaseOne(lhs: sample, rhs: sampleEmpty)

testCaseTwo(lhs: sample, rhs: sampleEmpty)

I prefer the other one, being idiomatic. But I rather not mutate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment