Bridging an array of enums from Swift to Objective-C

后端 未结 2 441
生来不讨喜
生来不讨喜 2021-01-18 06:59

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. I

相关标签:
2条回答
  • 2021-01-18 07:29

    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
    }
    
    0 讨论(0)
  • 2021-01-18 07:33

    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
    }
    
    0 讨论(0)
提交回复
热议问题