[英]IOS/Swift:syntax to return custom object in closure
I would like to place some JSON obtained asynchronously in an object and return in a closure. 我想将一些异步获取的JSON放在对象中,并在闭包中返回。 My code however is giving an error.
但是我的代码给出了错误。
func postToWebSwervice (aString:String,completion:@escaping (_ response:Array<Any>)->(MyObject)){
//get some JSON from web
let myObject = MyObject()
//parse JSON
myObject.title = "Palo Alto"
myObject.temp = 62
DispatchQueue.main.async {//open async
completion( myObject )
}
}
I am getting an error: 'Cannot convert object of type myObject to closure result type Void (aka ())
我收到错误消息:
'Cannot convert object of type myObject to closure result type Void (aka ())
I gather you cannot 'return' object. 我收集到您无法“返回”对象。 But what would correct syntax be to make it available to calling method upon completion?
但是正确的语法是什么,以便在完成时可用于调用方法?
Thanks for any suggestions. 感谢您的任何建议。
Replace Array<Any>
with MyObject
(you need to change your completion block syntax like thi) 用
MyObject
替换Array<Any>
(您需要更改完成块语法,例如thi)
func postToWebSwervice (aString:String,completion:@escaping (_ response: MyObject)-> Void){
//get some JSON from web
let myObject = MyObject()
//parse JSON
myObject.title = "Palo Alto"
myObject.temp = 62
DispatchQueue.main.async {//open async
completion( myObject )
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.