Created
January 26, 2021 16:14
-
-
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.
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
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