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()???
}
To use a function, you “call” that function with its name and pass it input values (known as arguments) that match the types of the function's parameters. A function's arguments must always be provided in the same order as the function's parameter list.
Swift static Methods In the previous example, we have used objects of the class to access its methods. However, we can also create methods that can be accessed without creating objects. These types of methods are called static methods. In Swift, we use the static keyword to create a static method.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With