通过索引访问字符串枚举 [英] Accessing a String Enum by index

查看:152
本文介绍了通过索引访问字符串枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C中有一个枚举,索引需要由一个String表示。



如何使用整数索引来使用Swift的String类型枚举? / p>

我想将枚举复制到Swift,将类型设置为字符串,并定义所有原始值以显示文本,然后使用C枚举值来提取Swift String枚举的原始值文本。



否则,我将只创建一个字符串数组。但枚举将更加可用。

$ b $在Swift中,枚举类型不包含其索引信息(至少不提供给程序员)。



所以:



如何通过整数索引使用Swift的String类型枚举?



答案是你不能。






你可以绑定 Int (或枚举案例)和 String 除了之外的其他方式,只需创建一个字符串数组。



例如,如果你的绑定的字符串可以与case标签相同,可以这样写:

 枚举MyEnum:Int {
case foo
case bar
case baz

var string:String {
return String(self)
}
}

如果let value = MyEnum(rawValue:0){
print(value.string)// - > foo
}

如果您的字符串需要更复杂一些以显示文本,您可以使用Swift 字典绑定枚举个案和字符串。

 枚举AnotherEnum:Int {
case foo
case bar
case baz

static let mapper:[AnotherEnum:String] = [
.foo:FooString,
.bar:BarString,
.baz:BazString
]
var string:String {
return AnotherEnum.mapper [self]!
}
}

如果let value = AnotherEnum(rawValue:1){
print(value.string)// - > BarString
}

比一个简单的字符串数组更可读。 p>

I have an enum in C and the index needs to be represented by a String.

How can a Swift enum of String type be used by integer index?

I would like to copy the enum to Swift, set the type to string and define all of the raw values to display text, and then use the C enum value to extract the raw value text for the Swift String enum.

Otherwise I will just create an array of strings.. But the enum would be more usable.

解决方案

In Swift, enum types do not hold its index info of cases (at least, not provided for programmers).

So:

How can a Swift enum of String type be used by integer index?

The answer is "You cannot".


You can bind Int (or enum cases) and String values in many ways other than just create an array of strings..

For example, if your bound Strings can be the same as case labels, you can write something like this:

enum MyEnum: Int {
    case foo
    case bar
    case baz

    var string: String {
        return String(self)
    }
}

if let value = MyEnum(rawValue: 0) {
    print(value.string) //->foo
}

If your Strings need to be a little more complex to display text, you can use Swift Dictionary to bind enum cases and Strings.

enum AnotherEnum: Int {
    case foo
    case bar
    case baz

    static let mapper: [AnotherEnum: String] = [
        .foo: "FooString",
        .bar: "BarString",
        .baz: "BazString"
    ]
    var string: String {
        return AnotherEnum.mapper[self]!
    }
}

if let value = AnotherEnum(rawValue: 1) {
    print(value.string) //->BarString
}

A little bit more readable than a simple array of strings.

这篇关于通过索引访问字符串枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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