小编use*_*563的帖子

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,因为我们将其设置为默认值。

有什么帮助吗?

xcode enums default-value associated-types swift

4
推荐指数
1
解决办法
1655
查看次数

标签 统计

associated-types ×1

default-value ×1

enums ×1

swift ×1

xcode ×1