在Swift中枚举具有相同值的多个个案 [英] Enum multiple cases with the same value in Swift

查看:308
本文介绍了在Swift中枚举具有相同值的多个个案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中,您可以让您的枚举具有以下含义:

In C you could make your enums have this:

typedef enum _Bar {
    A = 0,
    B = 0,
    C = 1
} Bar;

在Swift中,我想做等价的。但是,编译器抱怨它不是唯一的。如何告诉我我希望两个个案的值相同?

In Swift I want to make the equivalent. However, the compiler complains that it isn't unique. How do I tell it that I want two cases to have the same value?

enum Bar : Int {
    case A = 0
    case B = 0 // Does not work
    case C = 1
}

我已经尝试过

case A | B = 0

case A, B = 0

但是它似乎并没有按照我的意愿工作。

But it doesn't seem to work as I want it to.

推荐答案

Swift不支持重复值(或语义上的别名)。如果您不介意,则可以使用类似以下的方式模仿它:

Swift doesn't support duplicated values (or "aliases" semantically). If you don't mind, you can mimic it by using something like this:

enum Foo: Int {
    case Bar = 0

    static var Baz:Foo {
        get {
            return    Bar
        }
    }
    static var Jar:Foo {
        get {
            return    Foo(rawValue: 0)!
        }
    }
}

使用Swift的最新版本,可以将其缩短像这样:

With recent version of Swift, this can be shortened like this:

enum Foo: Int {
    case bar = 0

    static var baz:Foo { .bar }
    static var jar:Foo { Foo(rawValue: 0)! }
}

请注意,Swift已将其枚举变量的命名约定从 PascalCase camelCase

Note that Swift has changed their naming convention of enum variants from PascalCase to camelCase.

这篇关于在Swift中枚举具有相同值的多个个案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆