How to pass specific value to a cell when that cell is selected?

254 Views Asked by At

In short how to call performforsegue method inside didselect row for indexpath. I have an array and this array is the contents of tableView

`let array = ["USD","Inr", "AUD", "AED"]` 

and I have values for this array

let valueUSD = "65"
let valueInr = "10"
let valueAUD = "70"
let valueAED = "20"
 

I have another viewController with an optional string and a label and on the viewdidload I called

label.text = optionalstring //just a pseudocode but you get the idea

Now comes the problem, when the user selects USD I want the optionalstring to take the value of valueUSD variable and when he selects INR it should take valueInr variables value so on , so that the destination view controller will display this value, I don't know how to achieve this, how to gethold of selected indexpath.row and based on that how to set the value, for example

if indexpath.row == 0

`destinationViewController.optionalString = valueUSD`

I appreciate your attention.

1

There are 1 best solutions below

0
On BEST ANSWER

You should store your data in an array of your custom struct type:

let array = [
    MyData(name: "USD", number: "65"),
    MyData(name: "Inr", number: "10"),
    MyData(name: "AUD", number: "70"),
    MyData(name: "AED", number: "20"),
]

where MyData is like this:

struct MyData { // please give this a better name based on the data that you are working with!
    let name: String
    let number: String
}

You'd probably need to change your cellForRowAt method to set the cell's label text to array[indexPath.row].name rather than array[indexPath.row].

In didSelectRowAt:

let selectedData = array[indexPath.row].number
performSegue(withIdentifier: "insert your segue identifier here", sender: selectedData)

And then, override prepare(for:sender:):

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? TypeOfTheDestinationVC,
        let number = sender as? String {
        vc.optionalString = number
    }
}