Created
October 11, 2018 22:13
-
-
Save jakehawken/b549d4aeccb0333515ad521c8cee6b07 to your computer and use it in GitHub Desktop.
Optional assignment operator. (Discovered after writing this that it had already been thought of, suggested to, and rejected by Swift Evolution)
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 ??= | |
| func ??=<T>(lhs: inout T, rhs: T?) { | |
| guard let rhs = rhs else { | |
| return | |
| } | |
| lhs = rhs | |
| } | |
| // This collapses and obviates redundant-looking use of the nil coalescing operator | |
| // so that given this: | |
| var x: Int = 4 | |
| var optionalX: Int? = nil | |
| // instead of doing this: | |
| x = optionalX ?? x | |
| // you can instead do this: | |
| x ??= optionalX |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment