Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SwiftUI force-unwrap

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 }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading