Skip to content

Instantly share code, notes, and snippets.

@iThinker
Last active March 13, 2018 00:32
Show Gist options
  • Save iThinker/150caf4f6bf50e6d775c6b247225be5b to your computer and use it in GitHub Desktop.
Save iThinker/150caf4f6bf50e6d775c6b247225be5b to your computer and use it in GitHub Desktop.
class Trulean<T> {
class Empty: Trulean<T> {
override func onFalse(_ eval: @autoclosure () throws -> T) rethrows -> T {
return try eval()
}
}
class Full: Trulean<T> {
let _value: T
init(_ value: T) {
_value = value
}
override func onFalse(_ eval: @autoclosure () throws -> T) rethrows -> T {
return _value
}
}
func onFalse(_ eval: @autoclosure () throws -> T) rethrows -> T {
preconditionFailure()
}
}
class Falsean<T> {
class Empty: Falsean<T> {
override func onTrue(_ eval: @autoclosure () throws -> T) rethrows -> T {
return try eval()
}
}
class Full: Falsean<T> {
let _value: T
init(_ value: T) {
_value = value
}
override func onTrue(_ eval: @autoclosure () throws -> T) rethrows -> T {
return _value
}
}
func onTrue(_ eval: @autoclosure () throws -> T) rethrows -> T {
preconditionFailure()
}
}
extension Bool {
func onTrue<T>(_ eval: @escaping @autoclosure () throws -> T) rethrows -> Trulean<T> {
return self ? Trulean<T>.Full(try eval()) : Trulean<T>.Empty()
}
func onFalse<T>(_ eval: @escaping @autoclosure () throws -> T) rethrows -> Falsean<T> {
return self ? Falsean<T>.Empty() : Falsean<T>.Full(try eval())
}
func onTrue<T>(_ eval: @escaping @autoclosure () throws -> T) rethrows -> T? {
return self ? try eval() : nil
}
func onFalse<T>(_ eval: @escaping @autoclosure () throws -> T) rethrows -> T? {
return self ? nil : try eval()
}
}
let a = 1 > 0
let number: Int = a.onTrue(42).onFalse(0)
let optionalTrueString: String? = a.onTrue("Evaluated!")
let anotherOptionalString: String? = a.onFalse("Not evaluated")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment