Skip to content

Instantly share code, notes, and snippets.

@adam-zethraeus
Created January 10, 2022 03:50
Show Gist options
  • Save adam-zethraeus/36ca90160efeb931901c06beb24c035a to your computer and use it in GitHub Desktop.
Save adam-zethraeus/36ca90160efeb931901c06beb24c035a to your computer and use it in GitHub Desktop.
'GetOrSet' accessors for optionals and dictionaries
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