Last active
April 6, 2021 09:11
-
-
Save cristhianleonli/2e5ef0192d5ac650b4cf523b304827eb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import SwiftUI | |
// 1. The actual Decodable structure | |
struct CatFact: Codable { | |
// 2. nested codable structure | |
struct Status: Codable { | |
let verified: Bool | |
let sentCount: Int | |
} | |
let id: Int | |
let status: Status | |
let type: String | |
let text: String | |
let deleted: Bool | |
} | |
// 3. SwiftUI view, for the sake of simplicity and readability | |
struct ContentView: View { | |
@ObservedObject private var viewModel = ViewModel() | |
var body: some View { | |
VStack { | |
List { | |
ForEach(viewModel.facts, id: \.id) { fact in | |
Text(fact.text) | |
} | |
} | |
} | |
.onAppear { | |
viewModel.loadData() | |
} | |
} | |
} | |
// ViewModel which holds the data | |
class ViewModel: ObservableObject { | |
@Published var facts: [CatFact] = [] | |
// 4. fetch data | |
func loadData() { | |
// This data can come from any place, an api service or json file | |
let json = [ | |
[ | |
"id": 1, | |
"status": [ | |
"verified": true, | |
"sent_count": 1 | |
], | |
"text": "Most cats are lactose intolerant.", | |
"deleted": false, | |
"type": "cat" | |
], | |
[ | |
"id": 2, | |
"status": [ | |
"verified": false, | |
"sent_count": 2 | |
], | |
"text": "Most cats are lactose intolerant", | |
"deleted": true, | |
"type": "dog" | |
] | |
] | |
// 5. decoding the data | |
self.facts = [CatFact].parse(from: json, strategy: .convertFromSnakeCase) ?? [] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment