Last active
September 7, 2020 21:46
-
-
Save zackdotcomputer/462fdf95204bd0d5d1fa23f89b1c71fc to your computer and use it in GitHub Desktop.
More Monadical Optionals in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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