簡體   English   中英

如何使用@objc標記傳遞swift枚舉

[英]How to pass swift enum with @objc tag

我需要定義一個可以在使用某種Objective-c類型的類中調用的協議

但這樣做不起作用:

enum NewsCellActionType: Int {
    case Vote = 0
    case Comments
    case Time
}

@objc protocol NewsCellDelegate {
    func newsCellDidSelectButton(cell: NewsCell, actionType: NewsCellActionType)
}

你得到他的錯誤

Swift enums cannot be represented in Objective-C

如果我沒有將@objc標記放在我的協議上,那么只要它在一個采用協議並從Objective-C類型類(如UIViewController)繼承的類中調用它就會崩潰應用程序。

所以我的問題是,我應該如何使用@objc標簽聲明並傳遞我的枚舉?

Apple今天宣布,Swift 1.2(包含在xcode 6.3中)將支持將enum暴露給objective-c

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

在此輸入圖像描述

Swift枚舉與Obj-C(或C)枚舉非常不同,它們不能直接傳遞給Obj-C。

作為解決方法,您可以使用Int參數聲明您的方法。

func newsCellDidSelectButton(cell: NewsCell, actionType: Int)

並將其作為NewsCellActionType.Vote.toRaw()傳遞給它。 您將無法訪問Obj-C中的枚舉名稱,這會使代碼更加困難。

更好的解決方案可能是在Obj-C中實現枚舉(例如,在您的briding header中),因為它將在Swift中自動訪問,並且可以將其作為參數傳遞。

編輯

只需將@objc用於Obj-C類就不需要添加它。 如果您的代碼是純Swift,則可以使用枚舉而不會出現問題,請參閱以下示例作為證明:

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)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM