简体   繁体   English

扩展 class 中的 Var 显示错误“扩展不得包含存储的属性”

[英]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".当我将 var 移动到扩展中的新文件时,出现错误“扩展不得包含存储的属性”。 How can I solve it?我该如何解决? What is best way to "Clean up" var? “清理” var 的最佳方法是什么? Here my code:这是我的代码:

Class: Class:

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

Extension:扩大:

extension ReminderMain {
   var greeting = UILabel()
}

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).您真正需要的是遵循您的项目的架构,例如MVCMVPMVVM ,这些都是流行的(还有更多)。 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.现在对于您在上面解释的场景,您似乎有许多存储属性,例如var greeting = UILabel()您可能希望将它们移动到视图 class 并仅使用一个视图来设置 controller 的视图。 Here's an example (in MVC):这是一个示例(在 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.有关重构 go 的更多详细信息,请通过更好、更详细地解释这一点的教程。

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

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