Passing Data between Views

Hi all,

I am trying to create a weather app but i am struggling with passing data between views.

I have a lat & lon variable which by default is set to the current location of the user.

When the user selects to change location view they are able to select a new location, In which i need to be able to change the Lat & lon variable to the selected variables.

Could someone please help me with the most efficient way of doing this.

Thank you in advance
Answered by Claude31 in 653074022
How do you go from first view to second view ?

probably with a segue ?

If so, you need to use prepare function.
  1. Give an identifier to the segue, as CoordinatesSegue

  2. In the second view (the destination view), create var to hold the data to receive, such as:

var receivedLat : Double?
var receivedLon : Double?

Check the exact type (Float ? Double).
You could also use a t-uple (lat: Double, non: Double)?
Or an array if you pass several at once.

3. In the destination view, in viewDidLoad, load the appropriate IBOutlets with the content of those var, if not nil

4. In first view, write a prepare func:
Code Block
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
print(#function)
if segue.identifier == "CoordinatesSegue" {
if let destVC = segue.destination as? SecondController { // give the correct type : the destination controller
destVC.receivedLat = valueForLat
destVC.receivedLon = valueForLon
}
}
}


Accepted Answer
How do you go from first view to second view ?

probably with a segue ?

If so, you need to use prepare function.
  1. Give an identifier to the segue, as CoordinatesSegue

  2. In the second view (the destination view), create var to hold the data to receive, such as:

var receivedLat : Double?
var receivedLon : Double?

Check the exact type (Float ? Double).
You could also use a t-uple (lat: Double, non: Double)?
Or an array if you pass several at once.

3. In the destination view, in viewDidLoad, load the appropriate IBOutlets with the content of those var, if not nil

4. In first view, write a prepare func:
Code Block
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
print(#function)
if segue.identifier == "CoordinatesSegue" {
if let destVC = segue.destination as? SecondController { // give the correct type : the destination controller
destVC.receivedLat = valueForLat
destVC.receivedLon = valueForLon
}
}
}


Perfect, thank you
Passing Data between Views
 
 
Q