简体   繁体   English

Objective C&Swift互操作性导致错误“扩展可能不包含存储的属性”

[英]Objective C & Swift Interoperability causes error “Extensions may not contain stored properties”

I was working on one of my previous app that was done on Objective C. I need to add a new module to it and I decided to use Swift for that particular module. 我正在研究我在Objective C上完成的一个应用程序。我需要为它添加一个新模块,我决定将Swift用于该特定模块。

I have a class called HomePage in Objective C, I wanted to add some new IBAction s and IBOutlet s in it. 我在Objective C中有一个名为HomePage的类,我想在其中添加一些新的IBActionIBOutlet For that I added a new swift file and extended the existing class like: 为此我添加了一个新的swift文件并扩展了现有的类,如:

// MARK: IBOutlets and IBActions
extension HomePage
{
    @IBOutlet var image : UIImageView!
    ...

    /*!
    * Loads the application support webpage
    */
    @IBAction func loadSupportURL(sender : UIButton)
    {
    }
    ...
}

If I add only the IBActions everything is working perfectly. 如果我只添加IBActions,一切都很完美。 But when I add an IBOutlet, the compiler throws an error like: 但是当我添加一个IBOutlet时,编译器会抛出一个错误:

Extensions may not contain stored properties 扩展名可能不包含存储的属性

For fixing it I have two ways, 为了解决这个问题,我有两种方法,

  1. Declare the outlet in my Objective C class itself 在我的Objective C类中声明出口
  2. Convert the whole Objective C class to Swift and declare the property there 将整个Objective C类转换为Swift并在那里声明属性

Is there any other way to fix this issue ? 有没有其他方法可以解决这个问题?

As the error message clearly states, you can't have stored properties in an extension. 正如错误消息明确指出的那样,您不能在扩展中存储属性。 But the thing is, you can't have them in Objective-C categories either, so the language isn't the problem here. 但问题是,你不能在Objective-C类别中使用它们,所以这里的语言不是问题。

In both languages, you need to use associated references to implement stored properties. 在这两种语言中,您需要使用关联的引用来实现存储的属性。 Please see this thread for an example of using associated references in Swift. 有关在Swift中使用关联引用的示例,请参阅此主题 Since it is a C API, its usage is pretty much the same in Objective-C. 由于它是一个C API,它在Objective-C中的用法几乎相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM