简体   繁体   中英

Use function from one class in another class in Swift

So lets say I have a class called Math

class Math{

    func add(numberOne: Int, numberTwo: Int) -> Int{

        var answer: Int = numberOne + numberTwo
        return answer
    }

In this class there is a function which allows the user to add two numbers.

I now have another class which is a subclass of a UIViewController and I want to use the add function from the Math class, how do I do this?

class myViewController: UIViewController{

    //Math.add()???

}

If you want to be able to say Math.add(...) , you'll want to use a class method - just add class before func :

class Math{

    class func add(numberOne: Int, numberTwo: Int) -> Int{

        var answer: Int = numberOne + numberTwo
        return answer
    }
}

Then you can call it from another Swift class like this:

Math.add(40, numberTwo: 2)

To assign it to a variable i :

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

Use class keyword before add function to make it class function.

You can use

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

This code is from playgound.You can call from any class.

Swift 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()

  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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