从swift中的大括号返回函数

时间:2018-02-22 08:13:05

标签: swift

我需要从闭包中返回parseResult(String)作为函数结果。我怎么能在Swift中做到这一点? parseResult值不在函数范围内。

import Kanna

class Parse {

    class func parseFromWeb(parseUrl: String, xpath: String) {
        let url = URL(string: parseUrl)!
        let task = URLSession.shared.dataTask(with: url, completionHandler: { ( data , response , error ) in

            DispatchQueue.main.async{
                var serverString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)

                if let doc = Kanna.HTML(html: String(describing: serverString), encoding: String.Encoding.utf8) {
                    for parseResult in doc.xpath(xpath) {
                        print(parseResult)
                    }

                }
            }
        })
        task.resume()
        print("task.resume()")
    }

}

1 个答案:

答案 0 :(得分:1)

为您的方法添加完成处理程序:

class Parse {

class func parseFromWeb(parseUrl: String, xpath: String, completionHandler: (String?) -> ()) {
    let url = URL(string: parseUrl)!
    let task = URLSession.shared.dataTask(with: url, completionHandler: { ( data , response , error ) in

        DispatchQueue.main.async{
            var serverString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)

            if let doc = Kanna.HTML(html: String(describing: serverString), encoding: String.Encoding.utf8) {
                for parseResult in doc.xpath(xpath) {
                    // Call it here as this
                    comlpetionHandler(parseResult)
                    print(parseResult)
                }

            }
        }
    })
    task.resume()
    print("task.resume()")
}

}

然后你可以像这样使用它:

self.parseFromWeb(parseUrl: yourUrl, xpath: yourPath) { (parseResult) in
        //use parse result here
}

希望它有所帮助!!