Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
}
}
}
@Dschee

This comment has been minimized.

Copy link

commented Feb 13, 2017

Why is the method named then? When using it like the following it doesn't seem very readable to me:

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

I'd rather name it something like notNil of ifSome.

@NinoScript

This comment has been minimized.

Copy link

commented Feb 13, 2017

Isn't this just a map that doesn't return, and also doesn't work with handlers that return?

func then(_ handler: (Wrapped) -> Void) {
    map(handler)
}

You could easily make it work with functions that return other types:

func then<T>(_ handler: (Wrapped) -> T) {
    let _ = map(handler)
}

But even then the only reason for this to exist would be to improve semantics, but then isn't better than map as it incorrectly implies time.
Maybe apply?

@hashemp206

This comment has been minimized.

Copy link

commented Feb 14, 2017

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

image.ifSome {

}.else {

}
@dunqi

This comment has been minimized.

Copy link

commented Feb 14, 2017

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

@orxelm

This comment has been minimized.

Copy link

commented Feb 14, 2017

nice!

@asehgal123

This comment has been minimized.

Copy link

commented Feb 14, 2017

how about

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

This comment has been minimized.

Copy link

commented Feb 17, 2017

+1 for apply, @NinoScript !

@j4n0

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.