(Swift) 在 guard 语句中调用函数

(Swift) Call function in guard statement

我试图在保护语句中调用一个名为 'nextPage' 的函数,但它说“()”不能转换为 'Bool'。我需要做什么才能调用这个函数

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

你要么调用那个 returns 布尔值的函数,要么不要在 guard predicate 语句中做这样的事情,因为它不是调用函数的合适地方。 你应该做类似

的事情
guard variable != nil else {
    //handle nil case
}

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

guard 语句用于检查是否满足特定条件。 您不能在该语句中放置一个不 return true 或 false 的函数。

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

我相信你想要完成的是

@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

        }
}