【问题标题】:Swift 2: @objc protocol and enum arraySwift 2:@objc 协议和枚举数组
【发布时间】:2016-03-24 09:22:15
【问题描述】:

我有一个枚举定义如下:

@objc enum MyEnum: Int {
   case Case1, Case2
}

以及以下协议:

@objc protocol MyProtocol {
   func myFunc(myData: [MyEnum])
}

现在协议抛出以下错误:

 Method cannot be a member of a @objc protocol because the type of the parameter cannot be represented in Objective-C

我不明白为什么会这样。为什么会这样:

func MyFunc(myData: MyEnum)

但是会抛出数组错误?

我想过传递一个 Int 数组,然后将其转换回枚举,但我不太喜欢它。有没有更好的解决方案?

【问题讨论】:

    标签: ios swift enums swift2 protocols


    【解决方案1】:

    我不确定,但它应该不起作用,因为 Objective-C 数组应该只包含指针,而 Int 的枚举不包含指针。

    你可以试试这样的

    @objc enum MyEnum: Int {
        case Case1, Case2
    
        var numberValue : NSNumber {
    
            get {
    
                return NSNumber(
                    integer: self.rawValue
                )
            }
        }
    }
    
    @objc protocol MyProtocol {
        func myFunc(myData: [NSNumber])
    }
    

    【讨论】:

    • 是的,你是对的,我不认为 N​​SArray 必须只包含指针。至于解决方案,我将 for 循环移到函数外部,而不是在函数外部进行转换,然后再在函数内部进行转换
    猜你喜欢
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多