Search code examples
arraysswiftmultivalue

Swift Array with Only Two Possible Values


I want to create an array, let's say called nums and I want this array to hold either a Double or an Error value, and nothing else. Currently, I can get around the problem by instantiating nums as follows:

var nums = Array<(Double?, Error?)>()

Then I go through and do something like:

nums.append((5.0, nil))
nums.append((nil, Error.invalidNumber))
nums.append((10.0, nil))

This works, but instead of having nums have either a Double or an Error like I want, it has a tuple of those values. How can I change the instantiation of the array so that I only need to append one of the values to the array?

My goal is to be able to do this:

nums.append(5.0)
nums.append(Error.invalidNumber)
nums.append(10.0)

Solution

  • Result if the type for your needs. It is a generic enum whose value can either be success(Value) (where Value is Double for your case) or failure(Error).

    var nums = [Result<Double, Error>]()
    

    And then you can do:

    nums.append(.success(5.0))
    nums.append(.failure(Error.invalidNumber))
    nums.append(.success(10.0))