Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use function from one class in another class in Swift

Tags:

ios

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

}
like image 912
Stephen Fox Avatar asked Jul 23 '14 21:07

Stephen Fox


People also ask

How do you call a function in Swift?

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.

What is a static function Swift?

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.


1 Answers

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
like image 192
Undo Avatar answered Oct 02 '22 14:10

Undo