Skip to content

Instantly share code, notes, and snippets.

@zackdotcomputer
Last active September 7, 2020 21:46
Show Gist options
  • Save zackdotcomputer/462fdf95204bd0d5d1fa23f89b1c71fc to your computer and use it in GitHub Desktop.
Save zackdotcomputer/462fdf95204bd0d5d1fa23f89b1c71fc to your computer and use it in GitHub Desktop.
More Monadical Optionals in Swift
// Copyright © 2020 Zack Sheppard. All rights reserved.
// Available under the MIT License
/// A few Sequence/Monad-like functions added to Optional
extension Optional {
/// Transform this optional into another type
@inlinable public func map<T>(_ transform: (Wrapped) throws -> T) rethrows -> T? {
if let inside = self {
return try transform(inside)
} else {
return nil
}
}
/// Transform this optional into another type, collapsing that type's optional nature with this one's
@inlinable public func compactMap<T>(_ transform: (Wrapped) throws -> T?) rethrows -> T? {
if let inside = self {
return try transform(inside)
} else {
return nil
}
}
/// Filter this optional using an include pass function.
/// - Returns: `nil` if this is `nil` or if the `include` function returns `false` for the wrapped object.
@inlinable public func filter(_ include: (Wrapped) throws -> Bool) rethrows -> Wrapped? {
if let inside = self, try include(inside) {
return inside
} else {
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment