0

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

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

2 回答 2

2

守卫语句用于检查是否满足特定条件。您不能在该语句中放置不返回 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

        }
}
于 2017-09-21T15:59:04.843 回答
0

您应该调用返回布尔值的函数,或者不要在保护谓词语句中执行此类操作,因为它不是调用函数的合适位置。你应该做类似的事情

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

// continue work with variable, it is guaranteed that it’s not nil.
于 2017-09-21T15:53:15.530 回答