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

Leave a Reply

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