简体   繁体   English

对象可见的字符串枚举,但不是RawRepresentable

[英]Objc visible string enum but not RawRepresentable

I want to use enum that is visible both in objective C and Swift but not conform to protocol RawRepresentable. 我想使用在目标C和Swift中均可见但不符合协议RawRepresentable的枚举。

  1. I tried to have an enum of string both visible in Objc and Swift thus I use 我试图在Objc和Swift中都有一个可见的字符串枚举,所以我使用

    typedef NSString *myEnum NS_TYPED_ENUM;

  2. I tried to take advantage of the myEnum(rawValue: ) -> myEnum? 我试图利用myEnum(rawValue:)-> myEnum吗? function but I found the enumType has automatically conform to 函数,但我发现enumType已自动符合

    public struct myEnum : Hashable, Equatable, RawRepresentable { public init(rawValue: String) }

My question is how to create enum that is visiable in Objc and Swift but not conform to this protocol? 我的问题是如何创建在Objc和Swift中可见但不符合此协议的枚举? Thanks for all the help! 感谢您的所有帮助!

Swift Language Enhancements Swift语言增强

... Swift enums can now be exported to Objective-C using the @objc attribute. ...现在可以使用@objc属性将Swift枚举导出到Objective-C。 @objc enums must declare an integer raw type, and cannot be generic or use associated values. @objc枚举必须声明一个整数原始类型,并且不能为泛型或使用关联的值。 Because Objective-C enums are not namespaced, enum cases are imported into Objective-C as the concatenation of the enum name and case name. 因为没有为Objective-C枚举命名空间,所以枚举个案将作为枚举名称和个案名称的串联导入到Objective-C中。

Above From Xcode 6.4 Release Notes 以上来自Xcode 6.4发行说明


For this purpose you define the values in Objective-C, you can use the NS_TYPED_ENUM macro to import constants in Swift For example: .h file 为此,您可以在Objective-C中定义值,可以使用NS_TYPED_ENUM宏在Swift中导入常量,例如: .h文件

typedef NSString *const ProgrammingLanguage NS_TYPED_ENUM;

FOUNDATION_EXPORT ProgrammingLanguage ProgrammingLanguageSwift;
FOUNDATION_EXPORT ProgrammingLanguage ProgrammingLanguageObjectiveC;

.m file .m文件

ProgrammingLanguage ProgrammingLanguageSwift = "Swift";
ProgrammingLanguage ProgrammingLanguageObjectiveC = "ObjectiveC";

In Swift, this is imported as a struct as such: 在Swift中,将其作为结构导入:

struct ProgrammingLanguage: RawRepresentable, Equatable, Hashable {
    typealias RawValue = String

    init(rawValue: RawValue)
    var rawValue: RawValue { get }

    static var swift: ProgrammingLanguage { get }
    static var objectiveC: ProgrammingLanguage { get }
}

Although the type is not bridged as an enum, it feels very similar to one when using it in Swift code. 尽管该类型未作为枚举进行桥接,但在Swift代码中使用它时,它的感觉与之非常相似。

You can read more about this technique in the " Interacting with C APIs " of the Using Swift with Cocoa and Objective-C documentation 您可以在结合 使用Swift和Cocoa和Objective-C文档的“ 与C API交互 ”中阅读有关此技术的更多信息。

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

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