I am new in iOS and, right now, trying to implement my own init method in swiftui view. Init has one parameter and have to assign value to two States. But, whatever I do, it does not fill them properly. I use MapKit and CLLocationCoordinate2D for geolocation. Just to add, coordinates: CLLocationCoordinate2D in init has right value, but state has not. The view I am implement here is ModalView Any idea what to do? Here is my code.
@State var coordinate = CLLocationCoordinate2D()
@State private var name: String = ""
@State private var price: Decimal = 0
@State private var priceStr: String = ""
@State private var showAlert = false
@State private var location = ParkPlaceRespons(id: -1, name: "", price: -0, longitude: 18.42645, latitude: 43.85623)
@State private var mapArray = [ParkPlaceRespons]()
var alert: Alert{
Alert(title: Text("Error"), message: Text("Your price input is not in right format"), dismissButton: .default(Text("Ok")))}
init(coordinates: CLLocationCoordinate2D){
print(coordinates) // CLLocationCoordinate2D(latitude: 43.85613, longitude: 18.42745)
self.coordinate = coordinates
print(self.coordinate) // CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0)
self.coordinate.latitude = coordinates.latitude
self.coordinate.longitude = coordinates.longitude
self.location.longitude = coordinates.longitude
self.location.latitude = coordinates.latitude
print(location) // Does not work as well
self.mapArray.append(location)
print(mapArray) // Empty array
}
When you look into documentation about
@State
you will find this fragment:Therefore you should not set the coordinates, location or mapArray in the initializer, if you find that it is necessary to set the varaibles in the initializer you should either declare them as a
@Binding
or@ObservedObject
.