菜鸟教程小白 发表于 2022-12-11 16:53:04

ios - 如何将变量的值设置为从 Alamofire 收到的数据?


                                            <p><p>我有一个函数可以获取JSON格式的电影列表,如下:</p>

<pre><code>var size: Int = 0

func getMovies() {
    Alamofire.request(.GET, &#34;https://api.themoviedb.org/3/discover/movie&#34;, parameters: [&#34;sort_by&#34; : &#34;popularity&#34;, &#34;api_key&#34; : &#34;secret api key&#34;])
      .validate()
      .responseJSON { response in
            switch response.result {
            case .Success:
                self.json = JSON(response.result.value!)
                self.arraySize = self.json[&#34;results&#34;].count
                for num in 0...self.arraySize - 1 {
                  let x = self.json[&#34;results&#34;][&#34;popularity&#34;]
                  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) + &#34;:    &#34; + String(self.movieArray))
                }
                size = self.json[&#34;results&#34;].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) -&gt; ()) {

let someSize: Int!
//your code
case .Success:
               //your code
               let x = self.json[&#34;results&#34;][&#34;popularity&#34;]
                  self.movieArray.append(x.double!)
                someSize = self.json[&#34;results&#34;].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]
查看完整版本: ios - 如何将变量的值设置为从 Alamofire 收到的数据?