Hi there, I'm trying to learn Swift to do some basic user interfaces and I'm pulling my hair out trying to figure out something I feel should be fairly basic. I really hope someone can help me.
I have a view like the below:
ContentView.Swift
struct ContentView: View {
var body: some View {
// code...
}
}
I have my model for the JSON data:
TeamCollection.Swift
struct TeamCollection:Decodable {
let status: Int
let teams: [Team]
}
Plus I have a model for the individual teams as well:
Team.Swift
struct Team: Decodable {
var id:Int = 0
var name:String = ""
}
I'm trying to query an API that returns JSON data that I can then display within my view. I've gone over countless tutorials and none of them work in any way and I'm getting really worked up trying to figure this thing out.
The JSON you have shows an array of records, each record with two fields, status and "teams" which is an array of teams. I recon teams field can be absent in case of errors. You'd also want your Team "Identifiable" to use a teams array more easily with ForEach (and you conveniently already have a field called "id" which is Identifiable's requirement). To see how ForEach of Text views works - try it with a hardcoded array of teams first. Then with a hardcoded record (that has status and teams fields). Then with a hardcoded array of such records. Then with that data structure obtained by JSON decoding a hardcoded string, then with that string first decoded from a data (which you can mock via encoding a string). Then with that data obtained with URLSession from a URL – at that point you have the working sample which you can iterate over furthermore.
It would be better for you if you spend an hour trying to solve it yourself – just don't look for exact copy-pasteable tutorials on the web, try to do it yourself – that way you will master it. If feel lost - find some similar example or a few (e.g. one focusing on SwiftUI's ForEach, another on JSON decoding, another on URLSession, etc). Examples you've shown are ok (the last one I found pedagogically wrong, that style is more appropriate for a recipe book). I tend to like short examples laser focusing on a particular issue rather than full blown working apps. (Reminds me of my old practice of taking some sample code that goes into trouble implementing error checking and all the bells and whistles, etc, removing all error checking and other noise to see the wood for the trees, potentially distilling the sample down to a few relevant lines, and after that introducing whatever noise I see fit, be it error checking or higher level abstractions – you'd learn a lot doing this).
Questions like these are outside this forum domain, apple dev forums and stackoverflow are a better place.