Search code examples
iosswiftsegue

How to send multiple variables through segue


How can I send multiple variables through a segue in Swift? The QBBust gets sent over fine and prints on the view controller, but the QBName doesn't get sent over for some reason. Can anyone spot why?

        if let send = sender as? Double{
            destination.QBBust = send
        }
        if let sent = sender as? String{
            destination.QBName = sent
        }
    }
}

private var _QBName:String!
var QBName: String{
    get{
        return _QBName
    } set {
        _QBName = newValue
    }
}

private var _QBBust:Double!
var QBBust: Double {
    get {
        return _QBBust
    } set{
        _QBBust = newValue
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    let bust = String(Int(_QBBust))
    QBBustLabel.text = "\(bust)%"

    QBNameLabel.text = _QBName
}

This next part is in the button function that triggers the segue

performSegue(withIdentifier: "QBResultVC", sender: QBBust)

performSegue(withIdentifier: "QBResultVC", sender: QBName)

Solution

  • As in Tiago's answer, you can create a new struct or class which has QBName and QBBust properties. In addition, you can also use tuple in Swift.

    This is an example:

    in Destination ViewController

    declare var QBInfo:(name: String, bust: Double)?

    and in the button function that triggers the segue

    let QBInfo = (name: QBName, bust: QBBust)
    performSegue(withIdentifier: "QBResultVC", sender: QBBust) 
    

    then in prepareForSegue:sender:method

    destination.QBInfo = QBInfo