gpt4 book ai didi

swift - Alamofire for 循环在 Playgrounds 中返回空数组

转载 作者:行者123 更新时间:2023-11-28 15:40:54 25 4
gpt4 key购买 nike

我搜索了最后一个小时,但似乎无法弄清楚。我认输并询问。

我在下面有以下 playground 脚本,它打印了一个空数组。

我想在函数被调用时返回一个自定义对象数组。我读到 Alamofire 是异步的,但我现在真的不知道该怎么做。

提前致谢!

//: Playground - noun: a place where people can play

import UIKit
import Alamofire
import SWXMLHash
import PlaygroundSupport
import Foundation


PlaygroundPage.current.needsIndefiniteExecution = true
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)

class Tram {

var arrivalInMinutes: Int?
var tramDestinationEnglish: String?

init(destination: String, arrivalTime: Int) {
tramDestinationEnglish = destination
arrivalInMinutes = arrivalTime

}
}

func retrieveListOfTrams() -> [Tram] {

var anyArray = [Tram]()

Alamofire.request("https://hktramways.com/nextTram/geteat.php?stop_code=08W")
.response { (response) in

let xmlData = SWXMLHash.parse(response.data!)

for elem in xmlData["root"]["metadata"].all {
let tramArrival = elem.element!.attribute(by: "arrive_in_minute")!.text
let tramDestination = elem.element!.attribute(by: "tram_dest_en")!.text
anyArray.append(Tram(destination: tramDestination, arrivalTime: Int(tramArrival)!))

}

}
return anyArray


}

print(retrieveListOfTrams())

最佳答案

问题是您在请求返回结果之前返回了数组,因为当您阅读 Alamofire 时,它​​具有异步行为。解决这个问题的一种方法是使用一个完成 block ,它只会在结果到达后返回数组:

func retrieveListOfTrams(completion: @escaping ([Tram]) -> Void) {

var anyArray = [Tram]()

Alamofire.request("https://hktramways.com/nextTram/geteat.php?stop_code=08W")
.response { (response) in

let xmlData = SWXMLHash.parse(response.data!)

for elem in xmlData["root"]["metadata"].all {
let tramArrival = elem.element!.attribute(by: "arrive_in_minute")!.text
let tramDestination = elem.element!.attribute(by: "tram_dest_en")!.text
anyArray.append(Tram(destination: tramDestination, arrivalTime: Int(tramArrival)!))

}


completion(anyArray)
}

}

然后就可以调用函数了:

retrieveListOfTrams(completion: { anyArray in
print(anyArray.description)
})

关于swift - Alamofire for 循环在 Playgrounds 中返回空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43693769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com