使用Swift中另一个类中的一个类的函数

所以我要说我有一个名为Math的课程

class Math{ func add(numberOne: Int, numberTwo: Int) -> Int{ var answer: Int = numberOne + numberTwo return answer } 

在这个类中有一个允许用户添加两个数字的function。

我现在有另一个类,它是UIViewController的子类,我想使用Math类的add函数,我该怎么做?

 class myViewController: UIViewController{ //Math.add()??? } 

如果你想能够说Math.add(...) ,你会想要使用一个类方法 – 只需在func之前添加class

 class Math{ class func add(numberOne: Int, numberTwo: Int) -> Int{ var answer: Int = numberOne + numberTwo return answer } } 

然后你可以从另一个Swift类中调用它,如下所示:

 Math.add(40, numberTwo: 2) 

要将它分配给变量i

 let i = Math.add(40, numberTwo: 2) // -> 42 

add函数之前使用class关键字使其成为类函数。

您可以使用

 class Math{ class func add(numberOne: Int, numberTwo: Int) -> Int{ var answer: Int = numberOne + numberTwo return answer } } class myViewController: UIViewController{ //Math.add()??? //call it with class `Math` var abc = Math.add(2,numberTwo:3) } var controller = myViewController() controller.abc //prints 5 

这段代码来自playgound。你可以从任何一个class级打电话。

斯威夫特4:

 class LoginViewController: UIViewController { //class method @objc func addPasswordPage(){ //local method add(asChildViewController: passwordViewController) } func add(asChildViewController viewController: UIViewController){ addChildViewController(viewController) } } class UsernameViewController: UIViewController { let login = LoginViewController() override func viewDidLoad() { super.viewDidLoad() //call login class method login.addPasswordPage() } }