我有一个自定义对象的列表,我希望通过将其传递给函数来更改它的值: 我的代码如下:
func UpdateButtonPressed(_Url : String,referenceArray: inout Array<Item>)
{
var _itemList = [Item]()
var result:String! = ""
let url = URL(string:_Url)
var request = URLRequest(url: url! as URL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
guard data != nil else {
print("no data found: \(error)")
return }
do {
let temp = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
result = String(describing: temp!)
DispatchQueue.main.async {
referenceArray.append(contentsOf: self.UpdateItem(result:result))
}
}
})
task.resume()
}
func UpdateItem(result:String)-> [Item]
{
var _itemList = [Item]()
_itemList = Item.ConvertJSONToItemList(result: result)
return _itemList
}
我将我的功能调用如下:
var mostRecent = [Item]()
UpdateButtonPressed(_Url:PublicVariables.GetMostRecent(), referenceArray: &mostRecent)
但它没有用,我怎么能这样做?
答案 0 :(得分:0)
您可以尝试完成
func UpdateButtonPressed(_ Url : String , completion: @escaping (_ arr: [Item]) -> Void)
{
var _itemList = [Item]()
var result:String! = ""
let url = URL(string:_Url)
var request = URLRequest(url: url! as URL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
guard data != nil else {
print("no data found: \(error)")
return }
do {
let temp = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
result = String(describing: temp!)
DispatchQueue.main.async {
completion(self.UpdateItem(result:result))
}
}
})
task.resume()
}
像这样打电话
UpdateButtonPressed("") { (items) in
}
答案 1 :(得分:0)
问题的开始是你正在使用反模式。 您应该努力使您的功能成为第一级功能(输入和输出)。 你可以通过使用完成块或类似光明的未来或rx swift来解决这个问题。无论如何,你需要摆脱inout参数。
看一下这个链接:
https://thatthinginswift.com/completion-handlers/