Here is how you can call method or function in FirstViewController.swift from another Class called SecondViewController.swift in your iOS or macOS project within Xcode

Here is situation in your Xcode project that you want to call method from another class swift file to your original class of swift file.

 
Let’s call your original swift class file ‘FirstViewController’ which has ‘UIViewController’ as super class.

 
Second swift that you want to call function from we will assume that it has ‘SecondViewController’ as class name & it has ‘UIViewController’ as super class.

 
You have written function called ‘printSomething()’ in your ‘SecondViewController’ that would be triggered when somebody taps on button present on ‘FirstViewController’ as IBAction called ‘printThis(sender: UIButton)’

 
So you will write printThis function as follows:

 

SecondViewController().printSomething() // ViewControllerClassName().FunctionName()

 
So your ‘SecondViewController’ would look like this:

 

class SecondViewController: UIViewController {
    
    func printSomething() {
        print("printSomething function has been called")
    }
    
}

 
So your ‘FirstViewController’ would look like this:

 

class FirstViewController: UIViewController {

    @IBAction func printThis(sender: UIButton) {
        SecondViewController().printSomething() // ViewControllerClassName().FunctionName()
    }
}

 
Hope it helps,

 
Thanks & Regards
Mandar Apte

Mandar Apte

This website contains a design articles blog by Mandar Apte. He writes and shares his iOS development, graphic, web, & animation film design experience through articles. Mandar is Mumbai based multi-disciplinary designer with expertise in UI, UX, Logo, Symbol, and Brand Identity design. He is an alumnus of Sir J. J. Institute of Applied Art, Mumbai. He currently runs his studio in the heart of the city of Mumbai.

Leave a Reply

Your email address will not be published. Required fields are marked *