Codable

2021-08-14  本文已影响0人  王勋才
//
//  ContentView.swift
//  LearnCodable
//
//  Created by wangxuncai on 2021/8/14.
//

import SwiftUI
struct CustomerModel:Identifiable,Codable{
    //适用于基本数据类型,颜色不适用
    let id :String
    let name:String
    let points:Int
    let isPremium:Bool
    let r:Double
    let g:Double
    let b:Double
}
class CodableViewModel:ObservableObject{
    @Published var customer : CustomerModel? = nil
    
    init(){
        saveData()
        getData()
    }
    
    func getData() {
        guard let data =  UserDefaults.standard.data(forKey: "jsonData") else { return }
       // guard   let data = getJSONData() else {return}
        //把二进制数据还原成 顾客数据
        customer = try? JSONDecoder().decode(CustomerModel.self, from: data)
     
    }
    
    
    func saveData(){
        //初始化一个顾客
        let customer = CustomerModel(id: "abc", name: "Mike", points: 1000, isPremium: false, r: 0.9,g: 0.6,b: 0.3)
        
        //加密这这顾客数据成为二进制数据
        let jsonData = try? JSONEncoder().encode(customer)
        UserDefaults.standard.set(jsonData, forKey: "jsonData")
      
    }
}


struct ContentView: View {
   @StateObject var vm = CodableViewModel()
    var body: some View {
        VStack(spacing:20){
            if let customer = vm.customer{
                Text(customer.id)
                Text(customer.name)
                Text("\(customer.points)")
                Text(customer.isPremium.description)
                    .background(Color.init(red: customer.r, green: customer.g, blue: customer.b))
            }
        }
            .padding()
      
    }
}



上一篇下一篇

猜你喜欢

热点阅读