Skip to content

Instantly share code, notes, and snippets.

@NikhilManapure
Created October 29, 2017 10:07
Show Gist options
  • Select an option

  • Save NikhilManapure/e973337bacd1259c310032f7daa43c63 to your computer and use it in GitHub Desktop.

Select an option

Save NikhilManapure/e973337bacd1259c310032f7daa43c63 to your computer and use it in GitHub Desktop.

Revisions

  1. NikhilManapure created this gist Oct 29, 2017.
    29 changes: 29 additions & 0 deletions Optional.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    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