【问题标题】:(Swift) Call function in guard statement(Swift) 在保护语句中调用函数
【发布时间】:2018-03-03 01:22:26
【问题描述】:

我试图在保护语句中调用一个名为“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
        }
    }
}

【问题讨论】:

    标签: swift function methods guard-statement


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      guard variable != nil else {
          //handle nil case
      }
      
      // continue work with variable, it is guaranteed that it’s not nil.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多