【问题标题】:Getting non--void error on function return [duplicate]函数返回时出现非无效错误[重复]
【发布时间】:2019-07-08 04:14:14
【问题描述】:

我收到了这个错误,我知道这个问题之前已经通过人们没有将 return -> 添加到函数中来解决。我不明白为什么这仍然给我错误。

void 函数中出现意外的非 void 返回值

我正在尝试返回一个名为 message 的字符串。

     func ParseIt(proURL: String, startStr: String, stopStr: String) -> String {

        let url = URL(string: "https://www.siteimfetchingfrom.com/827444000973")

        let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in

            if error != nil {
                print(error)
            } else {
                let htmlContent = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                //print(htmlContent)
                // Get all Product Info
                //var proName = "id=\"productName\" value=\""

                if let contentArray = htmlContent?.components(separatedBy: startStr) {
                    //print(contentArray)
                    if contentArray.count > 0 {
                        //proName = "\" required"

                        let newContentArray = contentArray[1].components(separatedBy: stopStr)

                        if newContentArray.count > 0 {

                            let message = newContentArray[0]

                            //print(newContentArray)
                            print(newContentArray[0])

 return message // Error happens Here
                        }
                    }
                }

            }

        }
        task.resume()
    }

【问题讨论】:

    标签: swift


    【解决方案1】:

    仔细查看您的退货声明所属的位置。它不是从ParseInt 返回,它实际上是从传递给URLSession.shared.dataTask 的完成闭包返回。该完成处理程序的返回类型是void

    func dataTask(请求:URLRequest,completionHandler:@escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask

    【讨论】:

      【解决方案2】:

      return message 行写在闭包内。写在闭包内的 return 语句将从闭包中返回,而不是从周围的函数中返回。

      查看您如何执行网络请求并获得响应,您应该有一个完成处理程序而不是return。您不能立即从ParseIt 返回字符串,因为请求需要时间。

       // notice the extra completion parameter and the removal of the return type
       func ParseIt(proURL: String, startStr: String, stopStr: String, completion: @escaping (String) -> Void) {
      
          let url = URL(string: "https://www.siteimfetchingfrom.com/827444000973")
      
          let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
              ...
      
              // replace the return statement with this:
              completion(message)
          }
          task.resume()
      }
      

      你可以这样称呼它:

      ParseIt(proURL: ..., startStr: ..., stopStr: ...) {
          result in
      
          // do something with "result"
      }
      

      【讨论】:

        猜你喜欢
        • 2018-05-09
        • 2013-06-14
        • 1970-01-01
        • 2021-02-16
        • 1970-01-01
        • 2014-09-28
        • 2021-12-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多