Created
September 5, 2020 23:44
-
-
Save a-voronov/4fbb174cf1c753335c477d6533197df9 to your computer and use it in GitHub Desktop.
Optional built with Struct 🤪
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
/// Example of using static functions and properties to construct an instance of a type | |
/// for a struct, similar to how enum uses its cases. | |
/// Let's call it Maybe. | |
struct Maybe<Wrapped> { | |
private(set) var value: Wrapped! | |
var hasValue: Bool { | |
value != nil | |
} | |
private init(_ value: Wrapped!) { | |
self.value = value | |
} | |
func map<T>(_ transform: (Wrapped) -> T) -> Maybe<T> { | |
value == nil ? .none : .some(transform(value)) | |
} | |
func apply<T>(_ transform: Maybe<(Wrapped) -> T>) -> Maybe<T> { | |
transform.flatMap(map) | |
} | |
func flatMap<T>(_ transform: (Wrapped) -> Maybe<T>) -> Maybe<T> { | |
value == nil ? .none : transform(value) | |
} | |
static var none: Maybe { | |
Maybe(nil) | |
} | |
static func some(_ value: Wrapped) -> Maybe { | |
Maybe(value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment