尝试从函数[swift]外部调用时,数组返回空 [英] array return empty when trying to call from outside the function [swift]

查看:180
本文介绍了尝试从函数[swift]外部调用时,数组返回空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了这个调用api函数:

I got this calling api function:

func searchResults(){


    let urlString = "http://dev.jocom.com.my/feed"


    Alamofire.request(.POST, urlString , parameters: ["req" : "pro_name", "code" : searchString!])

        .responseData { response in

            switch response.result {
            case .Success:

                let apiSearchXML = SWXMLHash.parse(response.data!)

                for elem in apiSearchXML["rss"]["channel"]["item"]{
                    self.imageURL.append(elem["thumb_1"].element!.text!)

                    self.name.append(elem["name"].element!.text!)



                }
                print(self.name)

            case .Failure(let error):
                print(error)
            }
    }

}

当我打印输出时,似乎还可以,数组包含某些内容。但是,当我尝试调用它以显示在集合视图中时,它没有返回行,而是变为空,为什么呢?

It seems ok when i print the output out, the array its containing something. But when i try to call it to display inside my collection view, it didnt return row, and it become empty, why is it?

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {

    return 1
}


func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return self.name.count

}


func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! SearchResultsCollectionViewCell

    cell.titleLabel.text = "abc"
    cell.setNeedsDisplay()
    return cell
}


推荐答案

您的 Async 调用需要一个完成处理程序完成,然后可以将结果填充到数组中。我相信您的名称是一个字符串数组。这样做:

You need a completion handler for your Async call to complete and then you can fill the array with the results. I believe your name is an array of strings. Do like so:

func searchResults(complete: (names: [String]) -> ()){
let aVar = [String]()
//your code
for elem in apiSearchXML["rss"]["channel"]["item"]{

aVar.append(elem["name"].element!.text!)
}
complete(names: aVar)
//your code
}

然后在您调用它时,就像这样:

Then when you call it, like so:

searchResults { theNames in
 print(theNames)
//Here you have your array of names, use how you want.
}

这篇关于尝试从函数[swift]外部调用时,数组返回空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆