- Encoder + Decoder
Adoption Codable on any custom types enables us to serialize them to and from any of the built-in data formats by the Jdon Encoder and Json Decoder classes
- Codable API The Swift library defines a standardized approach to data encoding and decoding.
We need to adopt this approach by implementing the Encodable and Decodable protocols [Codable type alias] on your custom types.
1.To decode a local Json file to populate a SwiftUI view with this data.
2.To make this decoder function algorithm reusable anywhere.
3.To make this decoder a generics to decode any JSON file
// CodableBundleExtension.swift
// CodableBundleExtension
extension Bundle {
func decode(_ file: String) -> [CoverImage] {
// 1.Locate the json file
guard let url = self.url(forResource: file, withExtension: nil) else {
fatalError("Failed to locate \(file) in bundle")
}
// 2.Create a property for the data
guard let data = try? Data(contentsOf: url) else {
fatalError("Failed to load \(file) from bundle")
}
// 3.Create a decoder
let decoder = JSONDecoder()
// 4.Create a property for the decoded data
guard let loaded = try? decoder.decode([CoverImage].self, from: data) else {
fatalError("Failed to decode \(file) from bundle.")
}
// 5.Return the ready-to-use data
return loaded
}
}
// CoverImageView.swift
import SwiftUI
let coverImages: [CoverImage] = Bundle.main.decode("covers.json")
// MARK: - BODY
struct CoverImageView: View {
var body: some View {
TabView {
ForEach(coverImages) { item in
Image(item.name)
.resizable()
.scaledToFill()
} //: LOOP
} //: TAB
.tabViewStyle(.page)
}
}
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
List {
CoverImageView()
.frame(height: 300)
.listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
} //: LIST
.navigationBarTitle("한국 멸종위기 동물들", displayMode: .large)
.listStyle(.plain)
} //: NAVIGATION
}
}