我有一个函数来获取JSON格式的电影列表,如下所示:
var size: Int = 0
func getMovies() {
Alamofire.request(.GET, "https://api.themoviedb.org/3/discover/movie", parameters: ["sort_by" : "popularity", "api_key" : "secret api key"])
.validate()
.responseJSON { response in
switch response.result {
case .Success:
self.json = JSON(response.result.value!)
self.arraySize = self.json["results"].count
for num in 0...self.arraySize - 1 {
let x = self.json["results"][num]["popularity"]
self.movieArray.append(x.double!)
}
self.movieArray.sortInPlace()
for num in 0...self.arraySize - 1 {
let path = NSIndexPath(forRow: num, inSection: 0)
let cell = self.tableView.cellForRowAtIndexPath(path)
cell?.textLabel?.text = (self.findMovieByPopularity(self.movieArray[num]) + ": " + String(self.movieArray[num]))
}
size = self.json["results"].count
case .Failure(let error):
print(error)
}
}
}
在case .Success:
的末尾,我尝试将我在函数外部声明的变量size
设置为JSON中一个属性的长度。但是,当我在交换机外部使用此变量时,其值仍为0.
如何将size
设置为属性的长度,并且能够在函数外部使用它?
答案 0 :(得分:0)
添加一个完成处理程序并在闭包中分配值,如下所示:
func getMovies(completion: (aSize: Int) -> ()) {
let someSize: Int!
//your code
case .Success:
//your code
let x = self.json["results"][num]["popularity"]
self.movieArray.append(x.double!)
someSize = self.json["results"].count
}
completion(aSize: someSize)
//your code
然后当你想在其他函数调用中调用它时:
getMovies {numSize in
self.size = numSize
}