SoFunction
Updated on 2025-04-10

Swift refactoring custom null operator "??=" Example

1. Source of ideas

Recently, when I was doing Flutter development, I found an empty operator "??=" that I didn't notice before. It means that when the left is empty, the right value will be assigned to the left and then the left variable value is returned. It is often used to avoid multiple assignments. It was found that it is very practical, so I also customized a custom application for swift, and the end is as follows;

2. Example

b1 gets the value of a1, and if a1 is not empty, it will be assigned a value;

var a1: UIView?;
let b1 = a1 ??= UITableView();
print("a1: \(a1)");//a1: Optional(<UITableView: 0x7feda0830600;
print("b1: \(b1)");//b1: <UITableView: 0x7feda0830600

Equivalent to:

var a1: UIView?;
if(a1 == nil) {
    a1 = UITableView();
}
let b1 = a1;

This allows us to write one less line of code;

3. Source code

precedencegroup NilEqualPrecedence {
  /// Priority from left to right, left, right or none  associativity: left
  higherThan: AssignmentPrecedence//Priority, higher than equal sign operator  // lowerThan: AdditionPrecedence // Priority, lower than...  assignment: true // Is it an assignment operation}
/// Declaration of empty operatorinfix operator ??=: NilEqualPrecedence
/// Implementation of empty and so on operatorfunc ??= &lt;T&gt;(lhs: inout T?, rhs: T) -&gt; T {
    if lhs == nil {
        lhs = rhs;
    }
    return lhs!;
 }

4. Summary

One of Swift's most exciting features (although controversial) is the ability to custom operators.

When rewriting or defining new operators in your own code, make sure to follow these guidelines:

  • Don't create operators unless its meaning is obvious and indisputable. Find any potential conflicts to ensure semantic consistency.
  • Pay attention to the priority and correlation of custom operators, and only define new operator groups as needed.
  • If it makes sense, consider assigning variants to custom operator implementations.

The core of programming work is creation. Create all functions, tools, scripts that we need but do not have...

The above is the detailed content of the Swift refactoring custom empty operator "??=" instance. For more information about Swift refactoring custom empty operators, please pay attention to my other related articles!