swiftfunctionmethodsguard-statement

(Swift) Call function in guard statement


I am trying to call a function called 'nextPage' in a guard statement, but it is saying '()' is not convertible to 'Bool'. What do I need to do in order to call this function

@IBAction func nextPressed(_ sender: Any) {
    let geoCoder = CLGeocoder()
    geoCoder.geocodeAddressString(address) { (placemarks, error) in
        guard
            let placemark = placemarks?.first,
            let latVar = placemark.location?.coordinate.latitude,
            let lonVar = placemark.location?.coordinate.longitude,
            nextPage() // Error - '()' is not convertible to 'Bool'
            else {
                print("no location found")
                return
        }
    }
}

Solution

  • The guard statement is used to check if a specific condition is met. You cannot put a function that doesn't return true or false in that statement.

    Reference: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Statements.html

    I believe that what you are trying to accomplish is

    @IBAction func nextPressed(_ sender: Any) {
            let geoCoder = CLGeocoder()
            geoCoder.geocodeAddressString(address) { (placemarks, error) in
                guard
                    let placemark = placemarks?.first,
                    let latVar = placemark.location?.coordinate.latitude,
                    let lonVar = placemark.location?.coordinate.longitude
                    else {
                        print("no location found")
                        return
                }
    
                // will only get executed of all the above conditions are met
                nextPage() // moved outside the guard statement
    
            }
    }