Created
November 30, 2015 00:04
-
-
Save sam-w/157a63ae4f349cebaf39 to your computer and use it in GitHub Desktop.
Transforming ResultType<Value: CollectionType, Error> item by item
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
import Result | |
public extension ResultType where Value: CollectionType { | |
/// Returns a new Result by mapping each of `Success`es’ values using `transform`, or re-wrapping `Failure`s’ errors. | |
public func mapByItem<U>(@noescape transform: Value.Generator.Element -> U) -> Result<[U], Error> { | |
return flatMapByItem { .Success(transform($0)) } | |
} | |
/// Returns the result of applying `transform` to each of `Success`es’ values, or re-wrapping `Failure`’s errors. | |
public func flatMapByItem<U>(@noescape transform: (Value.Generator.Element) -> Result<U, Error>) -> Result<[U], Error> { | |
return analysis( | |
ifSuccess: { | |
$0.map(transform).reduce(.Success([])) { (acc, result) in | |
guard let successes = acc.value, success = result.value else { | |
return acc | |
} | |
return .Success(successes + [success]) | |
} | |
}, | |
ifFailure: Result<[U], Error>.Failure) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment