无法从函数内更改全局变量
Unable to change global variable from within function
我正在尝试从 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!)
}
}
假设 xml["rss"]["channel"]["item"] 不为零...
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])
}
self.setup()
}
}
func setup() {
// Your logic here
}
我正在尝试从 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!)
}
}
假设 xml["rss"]["channel"]["item"] 不为零...
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])
}
self.setup()
}
}
func setup() {
// Your logic here
}