【发布时间】:2017-10-17 00:46:07
【问题描述】:
我正在尝试从 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!)
}
}
【问题讨论】:
-
这是因为您甚至在 httpRequest 函数调用完成处理程序之前就打印了 self.projects。
-
Hmm.. 那么我怎样才能得到它,以便可以在 ViewDidLoad 中访问项目数组,其中包含正确的数据,以及在其他函数中?
-
为什么不把你的逻辑放在完成处理程序中?
-
我试过了,但是数组还是空的。你有一个例子吗?我一定是做错了
-
了解异步和同步之间的区别。搜索@escaping 函数。