0

I have a setup like this with an error shown below

enum DataError: Error { case failed(error: Error) } enum UIError: Error { case failed(error: Error) } struct SomeData { } func foo() -> AnyPublisher<Result<[SomeData]?, DataError>, Never> { ... } func foo2() -> AnyPublisher<Result<[SomeData]?, UIError>, Never> { return foo() .mapError { error -> UIError switch error { .... } return UIError.failed(error: $0) } .eraseToAnyPublisher() ===> // Error Cannot convert return expression of type 'AnyPublisher<Result<[SomeData]?, DataError>, UIError>' to return type 'AnyPublisher<Result<[T], UIError>, Never>' } 

The error message seem pretty straight forward but cant quite resolve it.

1
  • Without seeing your implementation of foo() this is largely pointless, as your code can never be tested in the compiler. Commented Mar 4, 2020 at 21:54

2 Answers 2

1

You will probably need something like this:

The Publisher returns no Error. The Result has the error so you need to mapError the Result.

I modified the Error enums a bit to make it easier to understand.

 enum DataError: Error { case failed } enum UIError: Error { case failed } func foo2() -> AnyPublisher<Result<[SomeData]?, UIError>, Never> { return foo().map { result in result.mapError { _ -> UIError in UIError.failed } }.eraseToAnyPublisher() } 
Sign up to request clarification or add additional context in comments.

Comments

0

There's no point in using Result in Combine, since your Publishers will always either emit a value or complete with failure. They should never emit a value, which contains an error.

Once you get rid of your usage of Result, the errors go away nicely.

func foo() -> AnyPublisher<[SomeData], DataError> { ... } func foo2() -> AnyPublisher<[SomeData], UIError> { return foo() .mapError { error -> UIError in switch error { ... } return UIError.failed(error: error) } .eraseToAnyPublisher() } 

Either with Result or in a Publisher, you usually don't need to use Optionals, since in case of error, there simply won't be a value, there's no need to return nil value, unlike with completion handlers.

3 Comments

Thanks @David for the suggestion; point taken, however it doesn't quite answer the questions. Do you have any response to resolving the current implementations error?
@user3355301 why do you want to fix a solution that has a fundamental flaw in it rather than fix that fundamental flaw?
There is a Result publisher so Result is useful — it is a publisher.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.