Skip to content

Instantly share code, notes, and snippets.

@PetrusM
Last active March 3, 2023 10:04
Show Gist options
  • Save PetrusM/8a8eadbd790e48a3f1b508895ea37262 to your computer and use it in GitHub Desktop.
Save PetrusM/8a8eadbd790e48a3f1b508895ea37262 to your computer and use it in GitHub Desktop.
Swift : Conditional assignment operators
// 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
}
}
@PetrusM
Copy link
Author

PetrusM commented Mar 3, 2023

?= : 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.

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