Last active
March 3, 2023 10:04
-
-
Save PetrusM/8a8eadbd790e48a3f1b508895ea37262 to your computer and use it in GitHub Desktop.
Swift : Conditional assignment operators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// MARK: - Not nulling assignment | |
precedencegroup NotNullingAssignment | |
{ | |
associativity: right | |
} | |
// This operators does only perform assignment if the value (right side) is not null. | |
infix operator =?: NotNullingAssignment | |
public func =?<T>(variable: inout T, value: T?) | |
{ | |
if let value = value | |
{ | |
variable = value | |
} | |
} | |
// This case is also necessary, because the previous one does not work is `variable` | |
/// is also optional, because in this case `T` would represent an optional. | |
public func =?<T>(variable: inout T?, value: T?) | |
{ | |
if let value = value | |
{ | |
variable = value | |
} | |
} | |
// MARK: - Not crushing assignment | |
precedencegroup NotCrushingAssignment | |
{ | |
associativity: right | |
} | |
// This operators does only perform assignment if the variable (left side) is null. | |
infix operator ?=: NotCrushingAssignment | |
public func ?=<T>(variable: inout T?, value: T) | |
{ | |
if variable == nil | |
{ | |
variable = value | |
} | |
} | |
/// This case is also necessary, because the previous one does not work is `variable` | |
/// is also optional, because in this case `T` would represent an optional. | |
public func ?=<T>(variable: inout T?, value: T?) | |
{ | |
if variable == nil | |
{ | |
variable = value | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
?=
: Assignment is performed only if the variable (left side) is null - it does not crush any value.=?
: Assignment is performed only if the new value (right side) is not null.