Skip to content

Instantly share code, notes, and snippets.

@a-voronov
Created September 5, 2020 23:44
Show Gist options
  • Save a-voronov/4fbb174cf1c753335c477d6533197df9 to your computer and use it in GitHub Desktop.
Save a-voronov/4fbb174cf1c753335c477d6533197df9 to your computer and use it in GitHub Desktop.
Optional built with Struct 🤪
/// 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