[Pitch]: Default values for enum associated values


(African Swift) #1

Swift enum cases with associated values are quite similar to function
parameters, except that currently flexible specification with enum
associated values, is only possible by using Parameter Objects.

The proposed solution is to enhance Swift enum associated values to support
default values in a functionally equivalent way to default parameters on
functions.

<https://gist.github.com/AfricanSwift/bfeab7d930785ed5096939ce24bd6cbf#detailed-design>Detailed
design

For example, let's say we define a person case with associated values for
firstname and surname:

enum ... {
   case person(firstname: String, surname: String)
}

... then down the line let's say we want to extend it with a person's
age, however
unlike functions, we're left only with imperfect options:

   - break the API
   - create a new case, e.g. person2(firstname: String, surname: String,
   age: Int)
   - re-implement case with a parameter object

Pitch

Should it be possible to assign defaults to *enum associated values*, with
a functional equivalence to function default parameter values (flexible
API), for example:

enum ... {
   case person(firstname: String, surname: String, age: Int? = nil)
}

Summary

Support defaults for enum associated values: to ensure that all the places
where the *associated value case* was used would continue to work when new
parameters (associated values) are added.


(Chris Lattner) #2

This is an additive proposal, thus out of scope for Swift 3. Please wait for post-swift-3 planning to start, which is after August 1.

-Chris

···

On Jul 18, 2016, at 12:49 PM, African Swift via swift-evolution <swift-evolution@swift.org> wrote:

Swift enum cases with associated values are quite similar to function parameters, except that currently flexible specification with enum associated values, is only possible by using Parameter Objects.