Swift Swift 4迁移后的类别“无可见接口”错误

问题描述:

我开始使用Xcode 9上的推荐向导对具有Objc和Swift一起工作的项目迁移项目。Swift Swift 4迁移后的类别“无可见接口”错误

extension UIColor { 
    func doSomething(withAnotherColor color: UIColor) -> Bool { 
     return true 
    } 
} 

然后在一些Objc类:

具有以下UIColor扩展时,会出现问题

@implementation MyView 

    - (void)styleView { 
     //... some code 
     if ([someColor doSomethingWithAnotherColor:anotherColor]) { 
      ... 
     } 
    } 
@end 

if声明抛出以下错误:../MyView.m: No visible @interface for 'UIColor' declares the selector 'doSomethingWithAnotherColor:'

我试着在扩展名和方法上使用@objc指令都没有运气。

注意这是一个编译错误,不喜欢提到的其他问题,像这样的警告:How can I deal with @objc inference deprecation with #selector() in Swift 4?

任何想法?

+3

您需要标记方法(或扩展)'@ objc';比较https://*.com/q/44390378/2976878 – Hamish

+0

对不起,我试了很多东西,包括(你提到的)之前发布的答案没有运气。 – Omer

+0

@matt只是修改了解释这个不同的问题。 – Omer

实质上,@ matt的解决方案是正确的方法。在我的特定情况下,另一种事情发生

这里的一些意见:

  • 无需前缀整个extension@objc,添加前缀功能只奏效了。
  • 正如在另一条评论中提到的那样,我在发布之前尝试过,但没有工作,但是由于@matt建议我决定删除所有驱动数据,重新打开项目并再次尝试,现在问题是另一回事点)
  • 显然职能从斯威夫特Objc翻译的方式已经改变了,我曾经有过:

斯威夫特(的UIColor类):

func doSomething(anotherColor: UIColor) -> Bool 

在objc更新之前,我是能够:

[aColor doSomething:anotherColor]; 

但更新后,我需要将其更改为:

[aColor doSomethingAnotherColor:anotherColor]; 

为了保持使用功能Objc以同样的方式,你可以改变斯威夫特功能:

func doSomething(_ anotherColor: UIColor) -> Bool 

这就是我最终的问题。 希望这可以帮助别人。

我在SWIFT功能的@objc注解明确指定方法签名解决了这一问题

// Swift codes 

@objc(myNoArgFunc) // need to specify even if the obj-c method name is the same as the swift name 
func myNoArgFunc() { 
} 

@objc(myFuncWithArg1:arg2:arg3:) // note the last : 
func myFunc(_ arg1: String, arg2: String, arg3: int) { 
}