How to pass swift enum with @objc tag

前端 未结 2 669
暗喜
暗喜 2020-12-09 02:11

I need to define a protocol which can be called in a class that use some Objective-c type

But doing that doesn\'t work:

enum NewsCellActionType: Int          


        
相关标签:
2条回答
  • 2020-12-09 02:14

    Apple just announced today that Swift 1.2 (included with xcode 6.3) will support exposing enums to objective-c

    https://developer.apple.com/swift/blog/

    enter image description here

    0 讨论(0)
  • 2020-12-09 02:31

    Swift enums are very different from Obj-C (or C) enums and they can't be passed directly to Obj-C.

    As a workaround, you can declare your method with an Int parameter.

    func newsCellDidSelectButton(cell: NewsCell, actionType: Int)
    

    and pass it as NewsCellActionType.Vote.toRaw(). You won't be able to access the enum names from Obj-C though and it makes the code much more difficult.

    A better solution might be to implement the enum in Obj-C (for example, in your briding header) because then it will be automatically accessible in Swift and it will be possible to pass it as a parameter.

    EDIT

    It is not required to add @objc simply to use it for an Obj-C class. If your code is pure Swift, you can use enums without problems, see the following example as a proof:

    enum NewsCellActionType : Int {
        case Vote = 0
        case Comments
        case Time
    }
    
    protocol NewsCellDelegate {
        func newsCellDidSelectButton(cell: UITableViewCell?, actionType: NewsCellActionType    )
    }
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate, NewsCellDelegate {
    
        var window: UIWindow?
    
        func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
            self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
    
            self.window!.backgroundColor = UIColor.whiteColor()
            self.window!.makeKeyAndVisible()
    
            test()
    
            return true;
        }
    
        func newsCellDidSelectButton(cell: UITableViewCell?, actionType: NewsCellActionType) {
            println(actionType.toRaw());
        }
    
        func test() {
            self.newsCellDidSelectButton(nil, actionType: NewsCellActionType.Vote)
        }
    }
    
    0 讨论(0)
提交回复
热议问题