8

Since Swift 1.2 it's been possible to automatically convert enums in Swift to Objective-C. However, as far as I can tell, it is not possible to convert an array of enums. Is this true?

So, this is possible:

@objc public enum SomeEnumType: Int {
    case OneCase
    case AnotherCase
}

But this is not:

public func someFunc(someArrayOfEnums: Array<SomeEnumType>) -> Bool {
    return true
}

Can anyone verify this? And how would you recommend working around this? One approach would be to have two method declarations e.g:

// This will not automatically get bridged.
public func someFunc(someArrayOfEnums: Array<SomeEnumType>) -> Bool {
    return true
}

// This will automatically get bridged.
public func someFunc(someArrayOfEnums: Array<Int>) -> Bool {
    return true
}

But this is polluting the Swift interface. Any way to hide the second function declaration for any Swift consumers?

Steffen D. Sommer
  • 2,896
  • 2
  • 24
  • 47
  • 1
    probably because you can't have an array of enums, in objective c you can only have an array of NSNumber. Int on the other hand can easily be bridged to NSNumber – Daniel Galasko May 26 '15 at 14:27

2 Answers2

17

It seems, we cannot expose Array<SomeEnumType> parameter to Obj-C even if SomeEnumType is @objc.

As a workaround, how about:

@objc(someFunc:)
func objc_someFunc(someArrayOfEnums: Array<Int>) -> Bool {
    return someFunc(someArrayOfEnums.map({ SomeEnumType(rawValue: $0)! }))
}

func someFunc(someArrayOfEnums: Array<SomeEnumType>) -> Bool {
    return true
}
rintaro
  • 51,423
  • 14
  • 131
  • 139
  • Ah, I didn't know that you could specify the method names for objc only using `@objc`. Pretty cool! It's still annoying, but this is definitely better. – Steffen D. Sommer May 26 '15 at 14:25
-2

Unfortunately an enum is not transferrable to Swift from Objective-C, it needs to be an NS_ENUM. I had the similar experience to you. The workaround I did was to create an Objective-C category that contains an NS_ENUM and there I transfer the values from the framework enum to my own NS_ENUM.

Import the category in your bridging header and you should be able to use the enum as you normally would do.

Something like this:

typedef NS_ENUM(NSUInteger, ConnectionStatus) {
    ConnectionStatusIdle
}

- (ConnectionStatus)connectionStatus {
    if [self getConnectionStatus] == WF_SENSOR_CONNECTION_STATUS_IDLE {
        return ConnectionStatusIdle
    }
}

Then you should be able to use it like this:

switch myObject.connectionStatus() {
    case .Idle:
        // do something
        break
}
EDUsta
  • 1,932
  • 2
  • 21
  • 30
ExpertAnd
  • 1
  • 1
  • I'm asking if it is possible to bridge an array of enums defined in Swift to Objective-C. And if not, what an elegant workaround could be. – Steffen D. Sommer May 26 '15 at 09:33