Default value for associated type enums in Swift
Asked Answered
M

1

5

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?

Mahaliamahan answered 18/6, 2022 at 11:39 Comment(1)
Okay, thanks Is there an alternative? So that there can be default values if nothing is mentioned?Mahaliamahan
C
15

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
Catron answered 18/6, 2022 at 11:55 Comment(2)
adding Stationary. prefix on a static property of the same type is redundant. static let pen = pen(brand: .brand1)Embolectomy
@LeoDabus Gosh you're right! I didn't expect that'd work at all! I totally thought there would be some sort of ambiguity issue, or the compiler mistakingly thinks that I'm using a property before its declared.Catron

© 2022 - 2024 — McMap. All rights reserved.