首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >for循环显示HTTP请求后总是最后一个数组值swift 3

for循环显示HTTP请求后总是最后一个数组值swift 3
EN

Stack Overflow用户
提问于 2019-06-03 06:29:35
回答 1查看 0关注 0票数 0

我已经使用另一个帖子来解决部分问题,所以现在我可以等待请求的结束了。我用Almofire发了一个http请求并解析生成的JSON文件。我认为myGroup.notify中的代码在请求完成后正确执行(如果我打印allCards.count则返回正确的值)。为什么我把for循环放在里面总是显示最后一张卡?

谢谢你的帮助

代码语言:javascript
复制
import UIKit
mport SwiftyJSON
import Alamofire

class ViewController: UIViewController {
//variables Declaration
var allCard = [Card]()
let allCardsHTTP: String = "https://omgvamp-hearthstone-v1.p.mashape.com/cards?mashape-key="

override func viewDidLoad() {
    super.viewDidLoad()
    let myGroup = DispatchGroup()

    //get HTTp request with Alamofire

    myGroup.enter()
    Alamofire.request(allCardsHTTP, method: .get).responseJSON {
         response in
         if response.result.isSuccess {
             let jsonCards : JSON = JSON(response.result.value!)
             print("success")
             self.updateJSONCards(json: jsonCards)
          }
        else {
             print("error")
         }
         myGroup.leave()
    }

    myGroup.notify(queue: .main) {
         //Updte UI here
         print(self.allCard[10].name) //This is Working

         for card in self.allCard {
            if card.cardsSet == "Basic" {
                print(card.name)
            }
        } //For loop always showing last card ???


    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


//MARK: - JSON Parsing


//Write the updateJSONCards method here:
func updateJSONCards(json: JSON) {
    //create the cards
     for (set, value) in json {
         var card = Card()
         card.cardsSet = set
         if json[set].count != 0 {
            for i in 0...json[set].count - 1 {
                card.name = json[set][i]["name"].stringValue
                allCard.append(card)
             }
         }
         else {
             print("The set \(set) has no cards")
         }
     }
  }

}

EN

Stack Overflow用户

发布于 2019-06-03 16:02:11

您正在Card错误的位置创建实例。

在内部重复循环之前,您将创建一个实例并将相同的实例附加到allCard数组。如果Card是类(引用语义),则该实例的所有实例都包含相同的数据(最后一个循环项)。

将两行放在重复循环中。

代码语言:javascript
复制
//Write the updateJSONCards method here:
func updateJSONCards(json: JSON) {
    //create the cards
     for (set, value) in json {
         if !json[set].isEmpty {
            for i in 0..<json[set].count {
                let card = Card()
                card.cardsSet = set
                card.name = json[set][i]["name"].stringValue
                allCard.append(card)
             }
         }
         else {
             print("The set \(set) has no cards")
         }
     }
  }
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100006895

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档