Search code examples
swiftsharednsobject

How to create a shared class and use it in another classes in swift


I need to use a shared class for my new project for reusing objects and functions in swift .I also need to know how this can be used in another classes. Thanks in Advance Berry


Solution

  • Here is a simple example of how to create 2 classes and using data and functions from 1st class in the 2nd class.

    first ViewController:

    class FirstViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let yourSharedValue: String = "Hello"
    }
    func yourSharedFunction() {
    print("your func")
    }
    

    second ViewController:

    class SecondViewController: UIViewController {
    let sharedData = FirstViewController() // assigning the data and functions from 1st view controller to variable 'sharedData'
    override func viewDidLoad() {
        super.viewDidLoad()
    let someString = sharedData.yourSharedValue // here you assign the value from 1st View controller to the value in 2nd view controller
    sharedData.yourSharedFunction() // here you call the function from 1st VC
    

    Hope it helps.