简体   繁体   English

Swift 中的 Objective-C 枚举

[英]Objective-C enum in Swift

I have the following enum in an Objective-C file:我在 Objective-C 文件中有以下枚举:

typedef NS_ENUM(NSInteger, countDirection){
    countDirectionUp = 0,
    countDirectionDown
};

How can I use this in a Swift view controller?如何在 Swift 视图控制器中使用它? I have tried this:我试过这个:

label.countDirection = countDirection.countDirectionDown

but I get an error:但我收到一个错误:

countDirection.Type does not have a member named countDirectionDown

These get translated to这些被翻译成

countDirection.Up
countDirection.Count

Swift removes as many letters as possible that the enum values have in common with the enumeration name. Swift 会删除尽可能多的枚举值与枚举名称相同的字母。 In your case, with an enumeration called countDirection and a value countDirectionUp, the whole "countDirection" is removed.在您的情况下,使用名为 countDirection 的枚举和值 countDirectionUp,删除整个“countDirection”。 It's not needed because you know which enum you are using, making your code considerable shorter.它不是必需的,因为您知道正在使用哪个枚举,从而使您的代码相当短。

With a bridging header and your enum values, I get the same error you do.使用桥接头和您的枚举值,我得到与您相同的错误。 However, if I change the enum values to:但是,如果我将枚举值更改为:

typedef NS_ENUM(NSInteger, countDirection) {
    cdUp = 0,
    cdDown

};

...then I don't get any errors. ...然后我没有收到任何错误。 For some reason, Swift does not like enum values that begin with the type name.出于某种原因,Swift 不喜欢以类型名称开头的枚举值。

No error with these enum values either:这些枚举值也没有错误:

typedef NS_ENUM(NSInteger, countDirection) {
    CountDirectioUp = 0,
    CountDirectionDown
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM