Objective C & Swift 互操作性导致错误 "Extensions may not contain stored properties"

Objective C & Swift Interoperability causes error "Extensions may not contain stored properties"

我正在开发我之前在 Objective C 上完成的应用程序之一。我需要向其中添加一个新模块,因此我决定对该特定模块使用 Swift。

我在 Objective C 中有一个名为 HomePage 的 class,我想在其中添加一些新的 IBActionIBOutlet。为此,我添加了一个新的 swift 文件并扩展了现有的 class,例如:

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

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

如果我只添加 IBActions,一切都运行良好。但是当我添加 IBOutlet 时,编译器会抛出如下错误:

Extensions may not contain stored properties

为了修复它,我有两种方法,

  1. 在我的 Objective C class 本身声明出口
  2. 将整个 Objective C class 转换为 Swift 并在那里声明 属性

还有其他方法可以解决这个问题吗?

正如错误消息明确指出的那样,您不能在扩展中存储属性。但问题是,您也不能将它们放在 Objective-C 类别中,因此这里的语言不是问题。

在这两种语言中,您都需要使用关联引用来实现存储属性。请参阅 this thread 以获取在 Swift 中使用关联引用的示例。因为它是 C API,它的用法在 Objective-C.

中几乎相同