簡體   English   中英

(快速)警衛聲明中的調用函數

[英](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
        }
    }
}

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

        }
}

您應該調用返回布爾值的函數,也不要在后衛謂詞語句中執行此操作,因為這不是調用函數的適當位置。 你應該做類似的事情

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM