Search code examples
iosswiftclasspropertiesvar

Var in extension class show error "Extensions must not contain stored properties"


Since I have many vars and I would like put in new file. When I move var to new file in extension, I got error "Extensions must not contain stored properties". How can I solve it? What is best way to "Clean up" var? Here my code:

Class:

class ReminderMain: UIViewController {
   override func viewDidLoad() {
      //Do something
   }
}

Extension:

extension ReminderMain {
   var greeting = UILabel()
}

Solution

  • What you actually need is to follow an architecture for your project like MVC, MVP or MVVM these are the popular ones (there are many more). These architecture enable you to clean up your code and maintain a structure for your project.

    Now for you scenario that you have explained above, you seem to have many stored properties like var greeting = UILabel() you might wanna move them into a view class and use only one view to set the view of the controller. Here's an example (in MVC):

    class ViewController: UIViewController {
        let myView = View()
        override func loadView() {
            super.loadView()
            view = myView
            myView.model = Model(greetingText: "My greeting")
        }
    }
    
    class View: UIView {
        var model: Model? {
            didSet { greeting.text = model?.greetingText }
        }
        var greeting = UILabel()
        override init(frame: CGRect) {
            super.init(frame: frame)
            addSubview(greeting)
            // add all other sub-views and layout them here
        }
    }
    struct Model { var greetingText: String }
    

    For more details about refactoring go through tutorials that explain this much better and in detail.