我正在尝试从 alamofire 变量中更改全局变量,但在执行此操作时遇到问题。这是我的代码:
var projects = [[String]]()
var xmlToParse = String()
var postTitle = String()
var postLink = String()
override func viewDidLoad() {
super.viewDidLoad()
httpRequest("https://www.hello.com/feed") { response in
self.xmlToParse = response as String
let xml = SWXMLHash.parse(self.xmlToParse)
for elem in xml["rss"]["channel"]["item"].all {
self.postTitle = elem["title"].element!.text
self.postLink = elem["link"].element!.text
self.projects.append([self.postTitle, self.postLink])
}
}
print(self.projects)
}
当我在这里打印 self.projects 时,我得到一个空数组,但是当我在 httpRequest 函数中打印它时,我得到了正确的数据。我没有在 for 循环中设置全局变量项目吗?如何获得该函数之外的值?我已经尝试了我在 SO 上找到的所有东西,但没有成功。任何帮助是极大的赞赏。
只是为了了解更多信息,这是我的 httpRequest 函数:
func httpRequest(_ section: String, completion: @escaping (String) -> Void) {
Alamofire.request(section, method: .get).responseString { response in
completion(response.result.value!)
}
}