1

I'm getting this error and I know this problem has been addressed on here before by people not adding the return -> to the function. I do not understand why this is still giving me error.

Unexpected non-void return value in void function

I'm trying to return a String called 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()
    }

2 Answers2

3

The line return message is written inside of a closure. A return statement written inside a closure will return from the closure, not the surrounding function.

Seeing how you are performing a web request and getting the response, you should have a completion handler instead of a return. You can't immediately return a string from ParseIt because the request will take time.

 // 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()
}

You can call it like this:

ParseIt(proURL: ..., startStr: ..., stopStr: ...) {
    result in

    // do something with "result"
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313
1

Look carefully where your return statement belongs. It's not returning from ParseInt, it's actually returning from the completion closure passed to URLSession.shared.dataTask. The return type of that completion handler is void.

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

Kon
  • 4,023
  • 4
  • 24
  • 38