Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

I have a class called HomePage in Objective C, I wanted to add some new IBActions and IBOutlets in it. For that I added a new swift file and extended the existing class like:

// 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. But when I add an IBOutlet, the compiler throws an error like:

Extensions may not contain stored properties

For fixing it I have two ways,

  1. Declare the outlet in my Objective C class itself
  2. Convert the whole Objective C class to Swift and declare the property there

Is there any other way to fix this issue ?

like image 799
Midhun MP Avatar asked Mar 16 '23 13:03

Midhun MP


1 Answers

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.

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. Since it is a C API, its usage is pretty much the same in Objective-C.

like image 121
Cihan Tek Avatar answered Apr 08 '23 22:04

Cihan Tek