Last active
October 15, 2020 00:32
-
-
Save rl-pavel/7bc81f0a84b92f57f82384b34989d16e to your computer and use it in GitHub Desktop.
Optional `get(orSet:)` helper extension.
This file contains 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
var foo: String? | |
var bar: String? = "bar" | |
print(foo) // nil | |
print(foo.get(orSet: "foo")) // foo | |
print(foo) // Optional("foo") | |
print(bar) // Optional("bar") | |
print(bar.get(orSet: "test")) // bar | |
print(bar) // Optional("bar") |
This file contains 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
extension Optional { | |
mutating func get(orSet expression: @autoclosure () -> Wrapped) -> Wrapped { | |
guard case let .some(item) = self else { | |
let newItem = expression() | |
self = .some(newItem) | |
return newItem | |
} | |
return item | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment