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

Sla*_*ion 1 methods class ios swift

我有一个 swift 类,其中包含大约 10 个不同的函数。它有 400 多行代码,需要分解。我想将一些函数放在不同的文件中。做这个的最好方式是什么?也许继承?

Dri*_*ris 5

您可以创建不同的文件,然后将一些方法放入其中extension

例子:

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

    func one(){
    }
    func two(){
    }
    func three(){
    }
} 
Run Code Online (Sandbox Code Playgroud)

然后创建一个新文件,并将更多函数放入该文件的扩展名中。

extension MyMessyViewController {

    func anotherFunctionFromThisExtension() {
       oneVariable = "I made this change from this File"
       print(oneVariable)
    }
}
Run Code Online (Sandbox Code Playgroud)

最佳实践如果你的视图控制器中有委托、集合/表视图,你可以用扩展将它们分开,而不是像这样简单的extension MyMessyViewController { }extension MyMessyViewController: UICollectionViewDelegate, UICollectionViewDataSource { }