Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Overload the '&&' AND & '||' OR Operators for Custom Swift Types
Written by Team Kodeco

In Swift, the && and || operators are used for performing logical operations, such as ‘and’ and ‘or’ respectively. When working with custom types in Swift, you may want to overload these operators to perform a similar operation specific to your custom type.

Here’s an example of how you might overload the && and || operators for a custom BoolWrapper class:

class BoolWrapper {
  var value: Bool
  init(_ value: Bool) {
    self.value = value
  }
}

extension BoolWrapper {
  static func && (left: BoolWrapper, right: BoolWrapper) -> BoolWrapper {
    return BoolWrapper(left.value && right.value)
  }
  static func || (left: BoolWrapper, right: BoolWrapper) -> BoolWrapper {
    return BoolWrapper(left.value || right.value)
  }
}

Now you can use the && and || operator to perform logical operations on instances of BoolWrapper:

let left = BoolWrapper(true)
let right = BoolWrapper(false)
var result = left && right
print(result.value) // false
result = left || right
print(result.value) // true

It’s important to note that overloading && and || operators should be used only when it makes sense for the custom types and the logical operation performed by them should be semantically consistent with the built-in logical operators.

© 2024 Kodeco Inc.