Skip to content

Instantly share code, notes, and snippets.

@janodev
Created February 18, 2017 10:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janodev/fa61bed87dca7b190d0b803fb179b249 to your computer and use it in GitHub Desktop.
Save janodev/fa61bed87dca7b190d0b803fb179b249 to your computer and use it in GitHub Desktop.
Chainable closures for optional types.
import Foundation
extension Optional
{
@discardableResult
func ifSome(_ handler: (Wrapped) -> Void) -> Optional {
switch self {
case .some(let wrapped): handler(wrapped); return self
case .none: return self
}
}
@discardableResult
func ifNone(_ handler: () -> Void) -> Optional {
switch self {
case .some: return self
case .none(): handler(); return self
}
}
}
struct Person {
let name: String
}
var p: Person? = Person(name: "Joe")
p.ifSome { print($0) }.ifNone { print("none") } // prints Person
p = nil
p.ifSome { print($0) }.ifNone { print("none") } // prints none
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment