我的導師讓我用 JSON 資料做一個簡單的挑戰。這個想法是提出問題“(國家)的首都是什么”,答案應該放在問題下面作為按鈕標題。
現在我已經做了:結構保存資料
struct Country : Codable{
var countries:[CountriesFinal]
}
struct CountriesFinal: Codable{
var country: String
var code: String
var capital: String
var region: String
}
要使用 URLSession 填充自定義日期型別 CountryFinal 的陣列:
var countriess = [CountriesFinal] ()
session.dataTask(with: url) {[self]data,response,error in
if let data = data {
if let decodedResponse = try?
JSONDecoder().decode(Country.self, from: data) {
DispatchQueue.main.async {
// update our UI
countriess = decodedResponse.countries
}
return
}
}
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()
這就是問題
他告訴我概念,我應該如何獲得國家及其首都的成對值,然后才能將它們打亂以進行包含國家的問題的測驗,4 個答案之一始終是我們要求的首都,其他答案是隨機首都:
從 x.country 和 x.capital 生成 y[i] : country 和 y[i] : capital。然后,當我有“y”時,我應該制作一個序列,例如 1...100,接下來要做的就是洗牌該序列。
所以聽了這個概念,我明白我需要制作包含國家和資本所有值的新陣列或字典,但我不知道該怎么做。我正在考慮像["France":"Paris"]這樣的字典,然后再制作另一個大寫字母陣列。
我已經學會了在使用 tableView 時如何訪問陣列中的物件,但現在我不知道從哪里開始或如何使用對值創建新陣列,因為現在當我嘗試 countrys.capital 或 country 時什么也沒有發生。
我真的不知道我還能怎么問這個問題,因為我很迷茫
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
performSelector(inBackground: #selector(fetch), with: nil)
askQuestion()
}
@objc func fetch(){
let urlString = "https://raw.githubusercontent.com/djakhdjkh/json"
let url = URL(string:urlString)!
URLSession.shared.dataTask(with: url) {[self]data,response,error in
if let data = data {
if let decodedResponse = try?
JSONDecoder().decode(Country.self, from: data) {
DispatchQueue.main.async {
// update our UI
countriess = decodedResponse.countries
print(countriess[0].name)
let index = Int.random(in: 0..<countriess.count)
print("What is the capital of \(countriess[index].name)?")
var choices = [index]
while choices.count < 3 {
let newIndex = Int.random(in: 0..<countriess.count)
if !choices.contains(newIndex) {
choices.append(newIndex)
}
}
choices = choices.shuffled()
print("Choices:")
choices.forEach { _ in print(countriess[index].capital) }
}
return
}
}
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()
uj5u.com熱心網友回復:
如果您想從您的國家/地區陣列中列印問題和可能的選擇,代碼可能如下所示:
let index = Int.random(0..<countries.count)
print("What is the capital of \(countries[index].country)?")
var choices = [index]
while choices.count < 3 {
let newIndex = Int.random(0..<countries.count)
if !choices.contains(newIndex) {
choices.append(newIndexP
}
}
choices = choices.shuffled()
print("Choices:")
choices.forEach { print($0.capital) }
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/365849.html
上一篇:RUBY:使用結構陣列
