
Photo by Sulthan Auliya on Unsplash
Queenstown, New Zealand
Press ‘Command + N’ to create a new Swift file named ‘Helper’
import Foundation
extension Bundle {
    func decode<T: Decodable>(_ type: T.Type, from file: String) -> T {
        guard let url = self.url(forResource: file, withExtension: nil) else {
            fatalError("Failed to locate \(file) in bundle.")
        }
        
        guard let data = try? Data(contentsOf: url) else {
            fatalError("Failed to load \(file) from bundle.")
        }
        
        let decoder = JSONDecoder()
        
        guard let loaded = try? decoder.decode(T.self, from: data) else {
            fatalError("Failed to decode \(file) from bundle.")
        }
        
        return loaded
    }
}
擴展了 Bundle 類型,增加了一個新的方法 decode,用於從 app 的 Bundle 中讀取並解碼 JSON 檔案。這種方法在 app 開發中常用於加載和解析存儲在 app bundle 內部的靜態資料。

改寫 PublicSwimmingPoolsView
struct PublicSwimmingPoolsView: View {
    
    let pools = Bundle.main.decode([PoolsSection].self, from: "pools.json")
    var body: some View {
        NavigationView {
            List {
                ForEach(pools) { (section) in
                    ForEach(section.items) { item in
                        NavigationLink(destination: PublicSwimmingPoolDetailView(publicSwimmingPool: item)) {
                            Text(item.name)
                        }
                    }
                }
            }
        }
        .navigationTitle(Text("Public Swimming Pools"))
        .navigationViewStyle(StackNavigationViewStyle())
    }
}
關於
let pools = Bundle.main.decode([PoolsSection].self, from: "pools.json")
Bundle.main:
decode([PoolsSection].self, from: "pools.json"):
Bundle 上的 decode 方法。decode 方法的第一個參數指定了你想解碼的數據的類型。在這裡,它是 [PoolsSection].self,這意味著你希望從 JSON 文件中解碼一個 PoolsSection 對象的陣列。"pools.json"。改寫 PublicSwimmingPoolDetailView
struct PublicSwimmingPoolDetailView: View {
    var publicSwimmingPool: PoolItem
    var body: some View {
        VStack {
            Text("Hello, \(publicSwimmingPool.name)")
            Image(publicSwimmingPool.photoCredit)
                .resizable()
                .scaledToFit()
            Text(publicSwimmingPool.description)
        }
    }
}

下集待續