Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access an enum in Swift from Objective-C?

There is a global enum defined in Objective-C:

typedef enum {
     UMSocialSnsTypeNone = 0,
     UMSocialSnsTypeQzone = 10,
     UMSocialSnsTypeSina = 11,                 //sina weibo
} UMSocialSnsType;

This code sets the sharetype of a platform:

snsPlatform.shareToType = UMSocialSnsTypeDouban;

In Swift, I want to get the sharetype of the platform:

var snstype = snsPlatform!.shareToType
println(snstype)

Result: UMSocialSnsType (has 1 child)

snstype.toRaw()

Error: UMSocialSnsType does not have a member named "toRaw"

like image 256
user3800029 Avatar asked Jan 10 '23 07:01

user3800029


1 Answers

From what I can tell, UMSocialSNSType was declared in Objective-C without using the NS_ENUM macro, so it wasn't imported as a Swift enum. That means that instead of being able to use .toRaw() or UMSocialSNSType.Douban you have to use the different enumeration values as constant structs. Unfortunately the type also doesn't have the appropriate operators (== or ~=) set up, so you have to compare the value property.

var snstype = snsPlatform!.shareToType

switch snstype.value {
case UMSocialSnsTypeDouban.value:
    println("douban")
case UMSocialSnsTypeEmail.value:
    println("email")
default:
    println("other")
}

if snstype.value == UMSocialSnsTypeDouban.value {
    println("douban")
}

The good news is that it looks like all the constants autocomplete in Xcode, so you should be able to do find the comparisons you need to do that way.


It looks like the Swift-version of the bridged typedef...enum must be something like:

struct UMSocialSnsType {
    var value:Int
    init(_ val:Int) {
        value = val
    }
}
let UMSocialSnsTypeNone  = UMSocialSnsType(0)
let UMSocialSnsTypeQzone = UMSocialSnsType(10)
let UMSocialSnsTypeSina  = UMSocialSnsType(11)
// etc

Whereas if it had been declared in Objective-C with the NS_ENUM macro, it would look like:

enum UMSocialSnsType: Int {
    case UMSocialSnsTypeNone = 0
    case UMSocialSnsTypeQzone = 10, UMSocialSnsTypeSina // etc.
}
like image 166
Nate Cook Avatar answered Jan 16 '23 20:01

Nate Cook