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
}
例如,默认值是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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
与函数参数相似,关联的值可以具有默认值:
类似于函数,必须像函数一样称呼cases,
()
后缀:如果您不喜欢
()< /code>后缀,您可以声明一些静态属性:
请注意,现在我们对
stastry.pen
的含义有一些歧义。它可能意味着具有类型(品牌) - &gt的功能。 Sentary
或具有类型stastary
的属性。不过,这通常很容易被歧义:Similar to function parameters, associated values can have default values:
Similar to functions, the cases have to be called like functions, with
()
suffixed:If you don't like the
()
suffix, you can declare some static properties: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 typeStationary
. This is typically easy to disambiguate though: