(Swift) Call function in guard statement

1.1k Views Asked by At

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

There are 2 best solutions below

0
On BEST ANSWER

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

        }
}
0
On

You should either invoke function that returns Boolean value, or do not do such thing inside guard predicate statement, because it’s not an appropriate place to call functions. You should do something like

guard variable != nil else {
    //handle nil case
}

// continue work with variable, it is guaranteed that it’s not nil.