How to pass data to another view when using performSegue in Swift 5

ODENZA
2 min readDec 17, 2020

--

In this article, I will show you how to pass parameters to another view when using performSegue in Swift 5 with example.

What I want?

When I click “Show” button on white view (First view), I want to send some datas like String, Int, dictionary data & etc… to my gray view (second view).

In this example, I will send dictionary data (String & Int) like this…

let sender: [String: Any?] = ["name": "My name", "id": 10]

How to do?

[Step 1]: Connect your first view and the second view.

[Step 2]: Add your Identifier, In this example my identifier is ShowSecondView

[Step 3]: Create button’s Show on the first view with code.

@IBAction func showButton(_ sender: UIButton) {   //Dictionary data that I want to send to the second view.  
let
sender: [String: Any?] = ["name": "My name", "id": 10]
// To go to the second view.
self.performSegue(withIdentifier: "ShowSecondView", sender: sender)
}

[Step 4]: Prepare for segue before pass data to another view.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {   if (segue.identifier == “ShowSecondView”) {      let secondView = segue.destination as! SecondViewController
let object = sender as! [String: Any?]
secondView.name = object[“name”] as? String
secondView.id = object[“id”] as? Int
}}

You can pass datas by dictionary type like…

secondView.myDictionary = sender as! [String : Any?]

But In this example, I will separate them and pass its.

[Step 5]: Declaring variables on the second view.

To pass datas to the second view class SecondViewController you have to declare name and id for receiving datas.

class SecondViewController: UIViewController {   //Declare variables to receive datas.
var
name: String?
var id: Int?
override func viewDidLoad() {
super.viewDidLoad()
print("My name:\(name ?? "") & my id: \(id ?? 0)") }
}

If you pass the datas from the first view func prepare by dictionary type, you also have to declare dictionary type in class SecondViewController like…

var dictionary: [String: Any?]?

When you run it, print result would be…

My name:My name & my id: 10

--

--

ODENZA
ODENZA

No responses yet