0

I'm writing a network layer, and, I wrote a enum to encapsulate the result of a request:

enum RequestResult<T> {
    case success(T)
    case error(RequestError)
}

For each request, I can have only success or fail. Then, I can use as this way:

class PostsRequest {
...
    static func fetch(completion: @escaping (RequestResult<[Post]>) -> Void) {

But, how I can use my generic RequestResult in requests that no have results on success, or have many results on success? I can write a generic enum with variable quantities in a case?

macabeus
  • 4,156
  • 5
  • 37
  • 66
  • You can change the success case to `case success([T])`, assuming all the results are of type `T` – Code Different Oct 27 '17 at 04:22
  • @CodeDifferent Well... I'm thinking to use tuple/struct. Then, if a request return two parameters, I can use `RequestResult<(String, Int)>`, for example. And, if a request return nothing, `RequestResult<()>`. But, maybe exists a better solution. – macabeus Oct 27 '17 at 04:27
  • You can use `RequestResult<(String, Int)>`. You can match it in `switch` statement using `case .success(let result as (String, int))` but it's better to define a struct for each result type you will get to make things clear – Code Different Oct 27 '17 at 04:35
  • I can write only `case .success(myString, myInt)`. Swift doesn't need type cast in this case. For example: https://pastebin.com/5h9Ju2KW – macabeus Oct 27 '17 at 04:43
  • The compiler doesn't complain but you can get a nasty surprise at run time. `myString` can be an `Int` and `myInt` can be a `String`. Without `as`, that case will match any 2-tuple. You have no clue what types the elements of these tuples are – Code Different Oct 27 '17 at 04:47
  • Ew... It's sounds like a compiler bug... Would you can reproduce this situation? I really don't know how to reproduce this bug (but, I'm trying now, for study purpose) – macabeus Oct 27 '17 at 04:52

1 Answers1

0

For requests that don't have results you can just use the Void type:

let request: RequestResult<Void> = .success()

For requests that have multiple results, i didn't quite understand your question, because in the example you provided, you are already modeling multiple results as an array:

RequestResult<[Post]>

If what you wanted was multiple results, each with different type, you should just put them inside a struct/class, and pass that type as a generic to your ResquestResult enum.

theffc
  • 21
  • 2