当来自模型时如何将数据保存在 userdefaults 中

How to save data in userdefaults when is from a model

我有这样的模特

struct House: Codable {
    let address: String?
    let rooms: String?
    let garage: Garage
}

struct Garage: Codable {
    let space: String?
    let numbers_of_ cars: String?
}

我从 api 获取数据并设置为可以显示它, 现在我需要在 userdefaults 中保存,以便在没有任何网络或 wifi 时显示信息

我正在这样尝试

var itemItems = [House]()

fileprivate func fetchData() {
        Service.shared.fetchCourses { (houses, err) in
            if let err = err {
                print("Failed to fetch houses:", err)
                return
            }

        self.itemItems = houses!

        var itemsToSave = [House]()
        for i in 0..<self.itemItems.count {
            itemsToSave.append(self.itemItems[i])
        }

        UserDefaults.standard.set(arrayToSave, forKey : "arrayToSave")

        }
    }

但是!!我得到一个错误 查看图片

https://i.ibb.co/bHhtj28/Captura-de-Pantalla-2019-11-24-a-la-s-4-25-18-p-m.png

您无法将自定义结构直接保存到 UserDefaults

但是由于两个结构都符合 Codable 编码它们

var itemItems = [House]()

fileprivate func fetchData() {
    Service.shared.fetchCourses { (houses, err) in
        if let err = err {
            print("Failed to fetch houses:", err)
            return
        }

        self.itemItems = houses!
        do {
           let data = try JSONEncoder().encode(self.itemItems)
           UserDefaults.standard.set(data, forKey : "houses")
        } catch { print(error) }      
    }
}