Generic Swift 4 enum with Void associated type

dr_barto picture dr_barto · Aug 23, 2017 · Viewed 17.5k times · Source

tl;dr

Is it possible to instantiate a generic Swift 4 enum member with an associated value of type Void?

Background

I'm using a simple Result enum (similar to antitypical Result):

enum Result<T> {
  case success(T)
  case error(Error?)
}

Now I'd like to use this enum to represent the result of an operation which does not yield an actual result value; the operation is either succeeded or failed. For this I'd define the type as Result<Void>, but I'm struggling with how to create the Result instance, neither let res: Result<Void> = .success nor let res: Result<Void> = .success() works.

Answer

Martin R picture Martin R · Aug 23, 2017

In Swift 3 you can omit the associated value of type Void:

let res: Result<Void> = .success()

In Swift 4 you have to pass an associated value of type Void:

let res: Result<Void> = .success(())
// Or just:
let res = Result.success(())