Default value for associated type enums in Swift

Viewed 149

I want to write code for an enum of stationary that takes default values when nothing is mentioned. Is it possible to do so in Swift?

Here's an example of what I'm trying to do

public enum Stationary: someStationaryClass {
    case pen (brand: Brands)
    case paper (brand: Brands)
    case pencil (brand: Brands)
}

public enum Brands {
    case brand1
    case brand2
}

Let's say the default value is brand1. So when I write

var item1 = Stationary.pen(brand: .brand2)

It is of brand2 but when I write

var item2 = Stationary.pen

It is of brand1 because we set that as the default value.

Any help?

1 Answers

Similar to function parameters, associated values can have default values:

public enum Stationary {
    case pen (brand: Brands = .brand1)
    case paper (brand: Brands = .brand1)
    case pencil (brand: Brands = .brand1)
}

Similar to functions, the cases have to be called like functions, with () suffixed:

let brand1Pen = Stationary.pen()

If you don't like the () suffix, you can declare some static properties:

public enum Stationary {
    case pen (brand: Brands)
    case paper (brand: Brands)
    case pencil (brand: Brands)
    
    static let pen = pen(brand: .brand1)
    static let paper = paper(brand: .brand1)
    static let pencil = pencil(brand: .brand1)
}

Note that now we have some ambiguities as to what Stationry.pen means. It could either mean the function with the type (Brands) -> Stationary, or the property with the type Stationary. This is typically easy to disambiguate though:

let brand1Pen: Stationary = .pen
Related