Skip to content

Instantly share code, notes, and snippets.

@freak4pc
Last active February 4, 2020 11:11
Show Gist options
  • Save freak4pc/ead00eba20d03b304b5ff70084e1e8f7 to your computer and use it in GitHub Desktop.
Save freak4pc/ead00eba20d03b304b5ff70084e1e8f7 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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