无法将对象追加到闭包内的数组



我是 swift 的新手,我想到构建一个显示实时比分的应用程序。 因此,为此,我正在使用Alamofire框架通过使用闭包来发出HTTP请求。

为了表示每个单场比赛得分和结果,我创建了以下名为"Score"的类:

class Score {
var homeTeamName : String = ""
var visitorTeamName : String = ""
var matchScore : String = ""
var matchTime : String = ""}

在 LiveScoresViewController 中,我声明并初始化了一个"Scores"类型的全局空集合,其中将存储实时比分

var scoresArray : [Score] = [Score]()

然后我创建两个方法:

  • getLiveScore : 发出 http 请求
func getLiveScores(url : String) {
Alamofire.request(url, method: .get).responseJSON { response in
if response.result.isFailure {
let alert = UIAlertController(title: "Error Occured", message: "Please check your connection or restart the application", preferredStyle: UIAlertController.Style.alert)
let alertAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.cancel)
alert.addAction(alertAction)
}
else {
let liveScoresJSON : JSON = JSON(response.result.value!)
self.updateLiveScore(json: liveScoresJSON)
}
}
}
  • updateLiveScore:解析JSON结果并表示它
func updateLiveScore(json : JSON) {
let size = json["result"].count
for index in 0..<size {
let match = Score()
match.homeTeamName = json["result"][index]["event_home_team"].string!
match.visitorTeamName = json["result"][index]["event_away_team"].string!
match.matchScore = json["result"][index]["event_final_result"].string!
match.matchTime = json["result"][index]["event_status"].string!
scoresArray.append(match)
}
}

getLiveScore 方法在 viewDidLoad(( 函数中调用,但 "scoresArray" 仍然为空,即使请求结果不是!我尝试在方法参数中传递集合,但我意识到我无法在 swift 中修改它,也不像 java,参数是常量。

首先最好使用Codable来解码响应

其次,对 api 的调用是异步的,这就是为什么它在viewDidLoad中是空的,因此您需要在将数据附加到数组后刷新闭包中的表/集合

最新更新