I set a variable swingPreviewLocation
in .inAppear()
but Swift forget’s it along the way. Printing the variable in the Map
view returns nil
.
However: Adding a Text()
into the body, then Swift remembers and prints
▿ Optional<Location>
▿ some : Location
- latitude : 48.026164457627125
- longitude : 11.958078424370319
Code:
import SwiftUI
import MapKit
struct SwingDetailView: View {
var swing: Swing
@State var swingPreviewLocation: Location? // Location is a struct
var body: some View {
VStack {
// This helps keep the variable. If I remove it, swift forgets the variable later.
if let latitude = swingPreviewLocation?.latitude,
let longitude = swingPreviewLocation?.longitude {
Text("Latitude: (Int(latitude)), Longitude: (Int(longitude))")
}
Map () {
let _ = print(self.swingPreviewLocation)
if let location = self.swingPreviewLocation {
Annotation("Club", coordinate: CLLocation(latitude: location.latitude, longitude: location.longitude).coordinate) {
Text("C")
}
}
}
.onAppear() {
self.swingPreviewLocation = swing.location
}
}
}
}
class Swing {
let location: Location?
init(location: Location?) {
self.location = location
}
}
struct Location {
var latitude: Double
var longitude: Double
}