Swift 中关联类型枚举的默认值

use*_*563 4 xcode enums default-value associated-types swift

我想为一个固定枚举编写代码,当没有提到任何内容时,该枚举采用默认值。在 Swift 中可以这样做吗?

这是我想做的一个例子

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

public enum Brands {
    case brand1
    case brand2
}
Run Code Online (Sandbox Code Playgroud)

假设默认值为brand1。所以当我写的时候

var item1 = Stationary.pen(brand: .brand2)
Run Code Online (Sandbox Code Playgroud)

它是brand2的,但是当我写的时候

var item2 = Stationary.pen
Run Code Online (Sandbox Code Playgroud)

它是brand1,因为我们将其设置为默认值。

有什么帮助吗?

Swe*_*per 12

与函数参数类似,关联值可以有默认值:

public enum Stationary {
    case pen (brand: Brands = .brand1)
    case paper (brand: Brands = .brand1)
    case pencil (brand: Brands = .brand1)
}
Run Code Online (Sandbox Code Playgroud)

与函数类似,案例必须像函数一样调用,并带有()后缀:

let brand1Pen = Stationary.pen()
Run Code Online (Sandbox Code Playgroud)

如果你不喜欢后缀(),你可以声明一些静态属性:

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)
}
Run Code Online (Sandbox Code Playgroud)

请注意,现在我们对于其Stationry.pen含义存在一些含糊之处。它可以表示具有 type 的函数(Brands) -> Stationary,也可以表示具有 type 的属性Stationary。但这通常很容易消除歧义:

let brand1Pen: Stationary = .pen
Run Code Online (Sandbox Code Playgroud)