init() {
let locations = ChurchLocationsDataService.locations
self.locations = locations
self.mapLocation = locations.first!
self.updateMapRegion(location: locations.first!)
}
Guys, tell me how I can safety unwrap this?
I’m trying to do this, but I get an error
init() {
let locations = ChurchLocationsDataService.locations
self.locations = locations
guard self.mapLocation = locations.first else { return }
guard self.updateMapRegion(location: locations.first) else { return }
}
>Solution :
You can simply provide a default if locations.first! fails:
init() {
self.locations = ChurchLocationsDataService.locations
// If locations.first fails, you can simply use some default
let firstLocation = ChurchLocationsDataService.locations.first ?? CLLocation(latitude: 0, longitude: 0)
self.mapLocation = firstLocation
self.updateMapRegion(location: firstLocation)
}
You can’t use the guard statements and return because the init() requires that everything be initialized. Failing in a guard means that isn’t the case.