Skip to content

Instantly share code, notes, and snippets.

@nanoxd
Last active December 30, 2018 11:13
Show Gist options
  • Save nanoxd/c3e3cfd6ca88ed9077e028cfa5d4288f to your computer and use it in GitHub Desktop.
Save nanoxd/c3e3cfd6ca88ed9077e028cfa5d4288f to your computer and use it in GitHub Desktop.
[Optional+Sugar] Adds nice ways to interact with optionals #swift
/// Type erased Optional protocol
protocol OptionalType {
associatedtype WrapType
var isSome: Bool { get }
var isNone: Bool { get }
var unsafelyUnwrapped: WrapType { get }
}
extension Optional: OptionalType {
/// Runs the closure if the item is available
func then(_ closure: (Wrapped) -> Void) {
if let wrapped = self { closure(wrapped) }
}
/// Returns true iff value is not nil
var isSome: Bool {
return self != nil
}
/// Returns true iff value is nil
var isNone: Bool {
return !isSome
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment