Skip to content

Instantly share code, notes, and snippets.

@rogerluan
Created January 26, 2021 16:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rogerluan/f4f8edba74e90697c59630d14c379bd4 to your computer and use it in GitHub Desktop.
Save rogerluan/f4f8edba74e90697c59630d14c379bd4 to your computer and use it in GitHub Desktop.
The Optional Value Setter operator assigns a value to the receiving subject, only if the receiver is nil. Analogous to Ruby's ||= operator.
infix operator ??=
extension Swift.Optional {
/// This is the Optional Value Setter operator. It assigns a value to the receiving subject, only if
/// the receiver is `nil`.
/// When the receiver is not `nil`, the value on the right hand side won't be accessed or computed (as
/// it's an `@autoclosure`). If the receiver already has `.some` value, no value will be assigned to it,
/// thus `willSet` and `didSet` won't be called.
///
/// - SeeAlso: the rejected proposal of this feature in Swift Evolution: https://github.com/apple/swift-evolution/blob/master/proposals/0024-optional-value-setter.md
public static func ??=(lhs: inout Self<Wrapped>, rhs: @autoclosure () -> Wrapped) {
guard case .none = lhs else { return }
lhs = rhs()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment