(Swift)在守卫声明中调用函数

时间:2017-09-21 15:46:40

标签: swift function methods 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
        }
    }
}

2 个答案:

答案 0 :(得分:2)

guard语句用于检查是否满足特定条件。 你不能在这个陈述中放置一个不会返回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

        }
}

答案 1 :(得分:0)

你应该调用返回布尔值的函数,或者不要在guard谓词语句中做这样的事情,因为它不适合调用函数。 你应该做点什么

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

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