Created
January 10, 2022 03:50
-
-
Save adam-zethraeus/36ca90160efeb931901c06beb24c035a to your computer and use it in GitHub Desktop.
'GetOrSet' accessors for optionals and dictionaries
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
import Foundation | |
public extension Optional { | |
mutating func getOrSet(builder: () -> Wrapped) -> Wrapped { | |
switch self { | |
case .some(let wrapped): | |
return wrapped | |
case .none: | |
let value = builder() | |
self = .some(value) | |
return value | |
} | |
} | |
} | |
public extension Dictionary { | |
mutating func getOrSet(key: Key, builder: () -> Value) -> Value { | |
self[key] ?? { | |
let value = builder() | |
self[key] = value | |
return value | |
}() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment