I have an Observable Object class to store a forecast object for my app
The class looks like this:
final class ForecastData: ObservableObject {
@Published var forecast: DarkSkyResponse
public func getForecast(at location: CLLocation) {
let request = DarkSkyRequest(key: "KEYGOESHERE")
let point = DarkSkyRequest.Point(location.coordinate.latitude, location.coordinate.longitude)
guard let url = request.buildURL(point: point) else {
//Handle this better
preconditionFailure("Failed to construct URL")
}
let task = URLSession.shared.dataTask(with: url) {
data, response, error in
DispatchQueue.main.async {
guard let data = data else {
//Handle this better
fatalError("No Data Recieved")
}
guard let forecast = DarkSkyResponse(data: data) else {
//Handle this better
fatalError("Decoding Failed")
}
self.forecast = forecast
}
}
task.resume()
}
init() {
self.getForecast(at: CLLocation(latitude: 37.334987, longitude: -122.009066))
}
}
The first part simply generates a URL to access the API by. Then I start a URLSession
which downloads the data and then parses it into a DarkSkyResponse
object. Finally I set the @Published
variable to the forecast object.
My problem is when I call the function in the initialiser, I get an error because the forecast property is not initialised. What is the best way to get around this? Where should I call the function? By the way I am using this class in my SwiftUI View using an @ObservedObject
property wrapper
Case1: use optional (and you need to handle it in View)
@Published var forecast: DarkSkyResponse?
Case2: use some default instance
@Published var forecast = DarkSkyResponse()
Both variants are equivalent and acceptable, so just by your preference.
Try this changes:
@Published var forecast: DarkSkyResponse!
and
init() {
super.init()
self.getForecast(at: CLLocation(latitude: 37.334987, longitude: -122.009066))
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.