Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding mapping over Results containing collections #123

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions Result/ResultType.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,27 @@ public extension ResultType {
}
}

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 map<U>(@noescape transform: Value.Generator.Element -> U) -> Result<[U], Error> {
return flatMap { .Success(transform($0)) }
}

/// Returns the result of applying `transform` to each of `Success`es’ values, or re-wrapping `Failure`’s errors.
public func flatMap<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)
}
}

// MARK: - Operators

infix operator &&& {
Expand Down
12 changes: 12 additions & 0 deletions ResultTests/ResultTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,16 @@ final class ResultTests: XCTestCase {
func testInitOptionalFailure() {
XCTAssert(Result(nil, failWith: error) == failure)
}

// MARK: Collections

func testCollectionMapTransformsSuccesses() {
XCTAssertEqual(successCollection.map { $0.characters.count } ?? [], [7, 14])
}

func testCollectionMapRewrapsFailures() {
XCTAssertEqual(failureCollection.map { $0.characters.count } ?? [], [])
}


// MARK: Errors
Expand Down Expand Up @@ -114,10 +124,12 @@ final class ResultTests: XCTestCase {
// MARK: - Fixtures

let success = Result<String, NSError>.Success("success")
let successCollection = Result<[String], NSError>.Success(["success", "anotherSuccess"])
let error = NSError(domain: "com.antitypical.Result", code: 1, userInfo: nil)
let error2 = NSError(domain: "com.antitypical.Result", code: 2, userInfo: nil)
let failure = Result<String, NSError>.Failure(error)
let failure2 = Result<String, NSError>.Failure(error2)
let failureCollection = Result<[String], NSError>.Failure(error)


// MARK: - Helpers
Expand Down