Skip to content

Instantly share code, notes, and snippets.

@riteshhgupta
Created February 6, 2017 18:33
Show Gist options
  • Save riteshhgupta/358db2ed3b6968ef18880cb28bdb6963 to your computer and use it in GitHub Desktop.
Save riteshhgupta/358db2ed3b6968ef18880cb28bdb6963 to your computer and use it in GitHub Desktop.
extension Optional {
// `then` function executes the closure if there is some value
func then(_ handler: (Wrapped) -> Void) {
switch self {
case .some(let wrapped): return handler(wrapped)
case .none: break
}
}
}
@haashem
Copy link

haashem commented Feb 14, 2017

how can I add another block for failure? I'm looking for something like this:

image.ifSome {

}.else {

}

@dungi
Copy link

dungi commented Feb 14, 2017

for the else part, just implement fun else() with ".none"-case i think

@orxelm
Copy link

orxelm commented Feb 14, 2017

nice!

@asehgal123
Copy link

asehgal123 commented Feb 14, 2017

how about

let age: Int? = 25
age.ifItHaz { print($0) }

@DivineDominion
Copy link

+1 for apply, @NinoScript !

@janodev
Copy link

janodev commented Feb 18, 2017

@hashemp206

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

@MKGitHub
Copy link

MKGitHub commented Apr 9, 2017

+1 for above

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment