Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Optional Unwrapping with Closures
public protocol OptionalType {
associatedtype Wrapped
var value: Wrapped? { get }
}
extension Optional: OptionalType {
public var value: Wrapped? {
return self
}
@discardableResult
public func then(_ closure: (Wrapped) -> Void) -> Optional {
if case .some(let item) = self {
closure(item)
}
return self
}
public func otherwise(_ closure: () -> Void) {
if case .none = self {
closure()
}
}
}
@freak4pc

This comment has been minimized.

Copy link
Owner Author

freak4pc commented Jul 13, 2017

Allows doing things like

MyObject(dependency1: xyz)
    .then { doSomethingWithObject($0) }
    .otherwise { print("This is nil") }

Or

MyViewController(dependency1: xyz)
    .then { [weak self] in self?.present($0, animated: true, completion: nil) }
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.