skip to Main Content

I am trying to build an app with several screens. Every screen should have different buttons which all call one function.

My problem is that I do not understand how to call one function from different view controllers with input parameters.
Also I want to have another variable defined accessible and changeable from every view controller.

This is what I kind of want my code to be:

import UIKit


var address = "address"


public func makeRequest(Command: String){
    
     let url = URL(address + Command)

     print(url)
    

}







class MainViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        

        let command = "command"
        
        makeRequest(Command: command)

        
    }


}



class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        print("address")

       address = "address2"

    


    }


}

2

Answers


  1. If all classes are view controllers put the method in an extension of UIViewController and the address constant in a struct

    struct Constant {
        static let address = "address"
    }
    
    extension UIViewController {
    
        public func makeRequest(command: String) -> URL? {
            guard let url = URL(string: Constant.address + command) else { return nil }
            print(url)
            return url
        }
    }
    
    Login or Signup to reply.
  2. extension UIViewController{
            func getName(name: String)-> String{
                print("hai (name)")
                return name
            }
        }
    

    you can write a extension for Viewcontroller and try to call the method like this. if you write the extension for viewcontroller you can directly call them with its reference

    self.getName(name:"Raghav")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search