Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equality on Objective-C typedef enum in Swift

Tags:

enums

swift

I'm working with the Facebook Objective-C SDK in Swift and I'm trying to compare an FBSessionState value with a value from the enum. However I get the compiler error:

Could not find an overload for '==' that accepts the supplied arguments

I'm essentially trying to accomplish:

if state == FBSessionStateOpen { ... }

I'm able to work around this by comparing against the value...

if state.value == FBSessionStateOpen.value { ... }

But I'm wondering if there is a way to make this work more like a Swift enum?

like image 244
Denny Ferrassoli Avatar asked Jun 10 '14 06:06

Denny Ferrassoli


People also ask

Can I use Swift enum in Objective C?

From what I understand, you can only import Swift stuff in . m files and there is no way to forward declare an enum in Objective C.

How do you declare an enum in Objective C?

Enums are defined by the following the syntax above. typedef NS_ENUM(NSUInteger, MyEnum) { MyEnumValueA, MyEnumValueB, MyEnumValueC, }; You also can set your own raw-values to the enumeration types. typedef NS_ENUM(NSUInteger, MyEnum) { MyEnumValueA = 0, MyEnumValueB = 5, MyEnumValueC = 10, };

What is typedef Objective C?

The typedef function is used to assign the new name to the datatype. So that you can use a custom name for predefined long names of the datatypes. This will not only save time but also aids in having more understandable and easy-to-read code.

What is Ns_enum?

Enumeration Macros }; The NS_ENUM macro helps define both the name and type of the enumeration, in this case named UITableViewCellStyle of type NSInteger . The type for enumerations should be NSInteger .


3 Answers

You could unwrap the enum and constants with '.value' to get the underlying integer, which should be switchable:

switch x.value {
  case Foo.value:
}

Maybe this is a bug and apple fix it in future releases.

like image 134
Nikolai Nagornyi Avatar answered Oct 01 '22 14:10

Nikolai Nagornyi


With the Beta4 update, the .value workaround no longer works. There doesn't seem to be another easy workaround without changing Facebook's SDK.

I changed all the Facebook enums to use the NS_ENUM macro, so that you can use Swift syntax the enums.

if FBSession.activeSession().state == .CreatedTokenLoaded

These changes were merged into pgaspar's Facebook fork, which includes other fixes for Swift compatibility.

pod 'Facebook-iOS-SDK', :git => 'https://github.com/pgaspar/facebook-ios-sdk.git'
like image 21
lsw Avatar answered Oct 01 '22 12:10

lsw


Adding to Nikolai Nagorny's answer, this is what worked for me:

if (device.deviceType.value == TYPE_BLUETOOTHNA.value)
like image 38
Vincil Bishop Avatar answered Oct 01 '22 12:10

Vincil Bishop