mimi93 mimi93 - 1 year ago 101
Swift Question

array return empty when trying to call from outside the function [swift]

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"]{



case .Failure(let 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"
return cell

Answer Source

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"]{

complete(names: aVar)
//your code

Then when you call it, like so:

searchResults { theNames in
//Here you have your array of names, use how you want.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download