ios - 如何将变量的值设置为从 Alamofire 收到的数据?
<p><p>我有一个函数可以获取JSON格式的电影列表,如下:</p>
<pre><code>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"]["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) + ": " + String(self.movieArray))
}
size = self.json["results"].count
case .Failure(let error):
print(error)
}
}
}
</code></pre>
<p>在 <code>case .Success:</code> 快结束时,我尝试将我在函数外部声明的变量 <code>size</code> 设置为 JSON 中一个属性的长度.但是,当我在 switch 之外使用这个变量时,它的值仍然是 0。</p>
<p>如何将 <code>size</code> 设置为属性的长度,并且还能够在函数之外使用它?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>添加一个完成处理程序并在闭包中分配值,如下所示:</p>
<pre><code>func getMovies(completion: (aSize: Int) -> ()) {
let someSize: Int!
//your code
case .Success:
//your code
let x = self.json["results"]["popularity"]
self.movieArray.append(x.double!)
someSize = self.json["results"].count
}
completion(aSize: someSize)
//your code
</code></pre>
<p>然后当你想在其他函数调用中调用它时:</p>
<pre><code>getMovies {numSize in
self.size = numSize
}
</code></pre></p>
<p style="font-size: 20px;">关于ios - 如何将变量的值设置为从 Alamofire 收到的数据?,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/38166440/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/38166440/
</a>
</p>
页:
[1]