本文介绍了Swift 2.0 Method 无法标记@objc 因为参数的类型无法在Objective-C中表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我将 Swift 1 更新到 Swift 2.0 后,我遇到了一个问题.

After I have updated Swift 1 to Swift 2.0 I have an issue.

我在此代码的第一行收到以下错误:

I am getting the following error on the first line of this code:

方法不能标记@objc,因为参数的类型不能在Objective-C中表示

@objc func personsToFirstStep(persons: [Person]) {
    for person in persons {
        if !self.persons.contains(person) && person.id != userID {
            self.persons.append(person)
        }
    }

    collectionView.reloadData()
    collectionViewPlaceholder.hidden = true
    collectionView.hidden = false
    collectionGradientView.hidden = false
} 

这个 Person 类:

This this Person class:

class Person: Hashable {

    var intID: Int = 0
    var id: String = ""
    var name: String = ""
    var type: String = ""

    var hashValue: Int {
        return self.intID
    }

    init(id: String, name: String, type: String) {
        self.id = id
        self.intID = Int(id)!
        self.name = name
        self.type = type
    }

}

func ==(lhs: Person, rhs: Person) -> Bool {
    return lhs.intID == rhs.intID
}

推荐答案

你自己很好地解释了这个问题:

You have very nicely explained the problem yourself:

class Person: Hashable {

Person 不是 NSObject.但是Objective-C只能看到NSObject派生的类类型.因此,您的 Person 类型对于 Objective-C 是不可见的.但是你的 @objc func 声明是针对一个接受 Person 数组的函数——我们刚刚说过 Person 对 Objective-C 是不可见的.所以你的 @objc func 声明是非法的.Objective-C 不能显示这个函数,因为它不能显示它的参数.

Person is not an NSObject. But only an NSObject-derived class type can be seen by Objective-C. Therefore your Person type is invisible to Objective-C. But your @objc func declaration is for a function that takes an array of Person — and we have just said that Person is invisible to Objective-C. So your @objc func declaration is illegal. Objective-C cannot be shown this function, because it cannot be shown its parameter.

您需要更改您的类声明以这样开始:

You would need to change your class declaration to start like this:

class Person: NSObject {

...然后您当然可能必须对类的实现进行任何必要的进一步调整.但是这种变化会使您的 @objc func 声明合法.(NSObject Hashable,因此进行这种调整所需的工作量可能不是很大.)

...and then you might of course have to make any necessary further adjustments in the class's implementation. But that change would make your @objc func declaration legal. (NSObject is Hashable, so the amount of work needed to make this adaptation might not be very great.)

这篇关于Swift 2.0 Method 无法标记@objc 因为参数的类型无法在Objective-C中表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 17:41