简体   繁体   English

如何在Swift中的不同文件中为类定义函数?

[英]How to define functions for class in different file in Swift?

I have a swift class that has about 10 different functions in it. 我有一个快速班,里面有大约10种不同的功能。 It's over 400 lines of code and needs to be broken up. 它超过400行代码,需要分解。 I want to put some functions in different files. 我想将一些功能放在不同的文件中。 What is the best way to do this? 做这个的最好方式是什么? Maybe inheritance? 也许继承?

You can create different files and then put some method in there within extension . 您可以创建不同的文件,然后在extension放入一些方法。

Example: 例:

class MyMessyViewController: UIViewController {
    var oneVariable: String = ""
    override func viewDidLoad() {
       super.viewDidLoad()
       anotherFunctionFromThisExtension()
    }

    func one(){
    }
    func two(){
    }
    func three(){
    }
} 

Then Create a new file and put more functions into this file within an extension. 然后创建一个新文件,并将更多功能放入扩展文件中。

extension MyMessyViewController {

    func anotherFunctionFromThisExtension() {
       oneVariable = "I made this change from this File"
       print(oneVariable)
    }
}

Best practice if you have Delegates, Collection/TableViews in you view controller, you can separate them with extensions, just instead of simple extension MyMessyViewController { } write like extension MyMessyViewController: UICollectionViewDelegate, UICollectionViewDataSource { } 最佳实践是,如果视图控制器中有Delegates,Collection / TableViews,则可以使用extension MyMessyViewController { }它们分开,而不是像简单的extension MyMessyViewController { }编写extension MyMessyViewController: UICollectionViewDelegate, UICollectionViewDataSource { }

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

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