for循环,始终显示HTTP请求后的最后一个数组值swift 3 [英] for loop cycle showing always the last array value swift 3 after HTTP request
问题描述
我已经用另一篇文章来解决问题的一部分,所以现在我可以等待请求结束.我使用Almofire发出了http请求,并解析了生成的JSON文件.我认为myGroup.notify中的代码在请求完成后正确执行(如果我打印allCards.count返回正确的值).为什么如果我将for循环放入其中总是显示最后一张卡片呢?
I already used another post to solver part of the problem,so now I am able to wait the end of the request. I made a http request with Almofire and parse the resulting JSON file. the code inside the myGroup.notify i think is correctly executed ater the request is completed (if I print allCards.count returns the correct value). Why if I put the for loop inside it is always showing the last card?
感谢您的帮助
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")
}
}
}
}
推荐答案
您在错误的位置创建了Card
实例.
You are creating the Card
instance at the wrong place.
在内部重复循环之前,您将创建一个实例并将相同实例附加到allCard
数组.如果Card
是类(引用语义),则该实例的所有出现都包含相同的数据(最后一个循环项).
Before the inner repeat loop you are creating one instance and appending the same instance to the allCard
array. If Card
is a class (reference semantics) all occurrences of that instance contain the same data (the last loop item).
将两行放入重复循环中.
//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")
}
}
}
这篇关于for循环,始终显示HTTP请求后的最后一个数组值swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!