Currently trying to get to print all strTeam from the teams:[Team] dictionary. Any guidance here will be appreciated.
If you see any other mistakes please let me know. Thank you.
import UIKit
class ViewController2: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("testing")
let url = "https://www.thesportsdb.com/api/v1/json/1/search_all_teams.php?l=English_Premier_League"
getData(from: url)
// Do any additional setup after loading the view.
}
func getData(from url:String){
let task = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: {data, response, error in
guard let data = data, error == nil else{
print("something went wrong")
return
}
// Received the data
var result: Response?
do{
result = try JSONDecoder().decode(Response.self, from: data)
}
catch{
print("failed to connect \(error.localizedDescription)")
}
guard let json = result else {
return
}
print(json.teams)
// WOULD LIKE TO ONLY PRINT all teams.strTeam HERE
})
task.resume()
}
}
struct Response: Codable {
let teams: [Teams]
}
struct Teams: Codable{
let strTeam : String
let strStadium : String
}
I have attempted json.teams.strTeam but get an error.
I know json.teams[i].strTeam gives me a single value but I would like all strTeam values printed.
This may be super easy but I just started learning Swift.
CodePudding user response:
You can map
the strTeam
values by doing this:
print(json.teams.map(\.strTeam))
The map
function takes an array and transforms it into a new array. In this case, we're taking the original array of Teams
and transforms it into an array of just the strTeam
property of each item.
CodePudding user response:
for name in json.teams {
print("WOULD LIKE TO ONLY PRINT all teams.strTeam HERE", name.strStadium)
}