10

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

}
Stephen Fox
  • 14,190
  • 19
  • 48
  • 52

3 Answers3

20

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
Undo
  • 25,519
  • 37
  • 106
  • 129
  • Thank you, but why did you take out the first argument name numberOne and kept the second one numberTwo in the function call? – Stephen Fox Jul 23 '14 at 21:51
  • 1
    It's a Swift nuance, @StephenFox. Swift leaves out the first parameter label to any function that isn't an init function. I explain it further in [this answer](http://stackoverflow.com/questions/24815832/when-are-argument-labels-required-in-swift/24815909#24815909). – Undo Jul 23 '14 at 21:52
3

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.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
codester
  • 36,891
  • 10
  • 74
  • 72
0

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

  }
}
Nupur Sharma
  • 1,106
  • 13
  • 15