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

发布于 2025-02-09 02:51:30 字数 524 浏览 1 评论 0原文

我想编写代码的固定枚举,该代码在没有提及的情况下占用默认值。可以在Swift中这样做吗?

这是我想做的示例,

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

public enum Brands {
    case brand1
    case brand2
}

例如,默认值是brand1。 因此,当我编写

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

它是brand2时,但是当我编写

var item2 = Stationary.pen

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

有帮助吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

感情洁癖 2025-02-16 02:51:30

与函数参数相似,关联的值可以具有默认值:

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

类似于函数,必须像函数一样称呼cases,()后缀:

let brand1Pen = Stationary.pen()

如果您不喜欢()< /code>后缀,您可以声明一些静态属性:

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)
}

请注意,现在我们对stastry.pen的含义有一些歧义。它可能意味着具有类型(品牌) - &gt的功能。 Sentary或具有类型stastary的属性。不过,这通常很容易被歧义:

let brand1Pen: Stationary = .pen

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文