我如何将数据传递给swift4中的变量? [英] How i can pass the data to a variable in swift4?
本文介绍了我如何将数据传递给swift4中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在另一个viewcontroller中使用输出数据,但是我不能使用,该字符串仅返回一个空字符串:
I need to use the output data in another viewcontroller but I can't use, the string only returns an empty string :
func callApi(postString: String) -> (String) {
var outputdata = String()
var req = LogIn(postString: postString)
let task = URLSession.shared.dataTask(with: req) { (data, response, error) in
if let data = data{
outputdata = String(data: data, encoding: String.Encoding.utf8)!
//print(outputdata)
}
}
print(outputdata)
return (outputdata)
}
推荐答案
您可以尝试此操作,因为该过程是异步的
You can try this as the process is asynchronous
func callApi(_ postString: String,completion:@escaping:(_ res:String?) -> Void ) {
var req = LogIn(postString: postString)
URLSession.shared.dataTask(with: req) { (data, response, error) in
if let data = data{
completion(String(data: data, encoding: String.Encoding.utf8))
}
else {
completion(nil)
}
}.resume()
}
致电
callApi("SendedValue") { res in
print(res)
}
这篇关于我如何将数据传递给swift4中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文