Reputation: 14470
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()???
}
Upvotes: 10
Views: 20364
Reputation: 1214
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()
}
}
Upvotes: 0
Reputation: 37189
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.
Upvotes: 3
Reputation: 25687
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
Upvotes: 20