Skip to content

Instantly share code, notes, and snippets.

@ast3150
Created October 7, 2016 12:29
Show Gist options
  • Save ast3150/c13a3f47743b4fdf22e1b43aa0581708 to your computer and use it in GitHub Desktop.
Save ast3150/c13a3f47743b4fdf22e1b43aa0581708 to your computer and use it in GitHub Desktop.
Swift: Assign Optional Operator
precedencegroup optionalAssignPrecedence {
associativity: left
higherThan: AssignmentPrecedence
}
/// If rhs has a value, assigns rhs to lhs
/// If rhs is an empty optional, does nothing
infix operator ?= : optionalAssignPrecedence
func ?=<T: Any>(lhs: inout T, rhs: T?) {
if let rhs = rhs {
lhs = rhs
}
}
@ast3150
Copy link
Author

ast3150 commented Oct 7, 2016

Example of usage:

var left = "Before"

let empty: String? = nil
let notEmpty = "After"

left ?= empty // Right side is empty, do nothing
print(left) // Prints "Before"

left ?= notEmpty // Right side has value, assign to left
print(left) // Prints "After"

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