This post is about very common scenario in which we have to pass data from one screen to another.

There are various methods to do so but from that I am writing about simple and clean way by creating data model class to follow my rule of development “Code simple and clean”.

Scenario

1. We have to class Class A and Class B

2. We have to send multiple data  from Class A to Class B  (name, age, sex)

3. We are taking one Button on Class A to navigate to Class B  (I am navigating using segue, you can use any  preferred way)

We need three classes

1. Model.swift – data model class to store data

2. Class A – from which we are sending data to Class B

3. Class B – To which are getting data from Class A

1. Model.swift

In this class we are creating variables who will store data we have to pass from one class to another

import Foundation

class Model : NSObject{
    
    var name :String?
    var age :Int?
    var sex :String?  
}

2. Class A

From this class we are passing data to Class B on button click

import UIKit

class A: UIViewController {
    
    let model = Model()
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        model.name = "Mac"
        model.age = 23
        model.sex = "male"
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let newV = segue.destination as! NewViewController
        newV.model = model
    }
}

3. Class B

In this class we are printing values getting from Class A

import UIKit
class B: UIViewController {

    var model = Model()
    override func viewDidLoad() {
        super.viewDidLoad()

        print("Name (models.name!)")
        print("Age (models.age!)")
        print("Sex (models.sex!)")
    }
}

 

240_F_77959340_hWLiOY93juohUoXqjKzqPB79552nw8XU

Hope you find this blog useful. Please feel free to contact with me in case you have any query, suggestions.  You can comment, like and follow posts.

You can request any topic related to Swift and iOS development.

Donate any small amount you think for this knowledge to grow this forum.                        

To Donate –  paypal.me/SandeshSardar

download

Advertisements