import Foundation
let userModelFilePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! + "/userModelData"
struct UserModel:Codable {
var name: String = ""
var age: String = ""
var sex: String = ""
var weight: Float = 0
var work: String?
private enum CodingKeys: String, CodingKey {
case name
case age
case sex
case weight
case work
}
init(name: String, age: String, sex: String, weight: Float, work: String?) {
self.name = name
self.age = age
self.sex = sex
self.weight = weight
self.work = work
}
// func encode(to encoder: Encoder) throws {
// var container = encoder.container(keyedBy: CodingKeys.self)
// do {
// try container.encode(name, forKey: .name)
// try container.encode(age, forKey: .age)
// try container.encode(sex, forKey: .sex)
// try container.encode(weight, forKey: .weight)
// try container.encode(work, forKey: .work)
// }catch {
//
// }
// }
// init(from decoder: Decoder) throws {
// do {
// let container = try decoder.container(keyedBy: CodingKeys.self)
// name = try container.decode(String.self, forKey: .name)
// age = try container.decode(String.self, forKey: .age)
// sex = try container.decode(String.self, forKey: .sex)
// weight = try container.decode(Float.self, forKey: .weight)
// work = try container.decode(String.self, forKey: .work)
// }catch {
//
// }
// }
}
class UserModelTool {
class func saveUser(_ user: UserModel) {
let encoder = JSONEncoder()
do {
let data = try encoder.encode(user)
try data.write(to: URL(fileURLWithPath: userModelFilePath))
}catch {
}
}
class func user() -> UserModel? {
let decoder = JSONDecoder()
let fileManager = FileManager.default
guard let data = fileManager.contents(atPath: userModelFilePath) else {
return nil
}
do {
let user = try decoder.decode(UserModel.self, from: data)
return user
}catch {
}
return nil
}
}
网友评论