我有一个模型课
class User{
var name:String
var number:Int
}
我将其详细信息下载为文本文件,格式为
firstname:John
rollnumber:234
5
我该如何为此定制装饰器。
NB:键“ firstname”“ rollnumber”是动态的,是从后端获取的。
答案 0 :(得分:0)
这样解析,将响应作为Dict
传递给init
方法
class User{
var name:String?
var number:Int?
init(With dict:[String:Any]){
if let value = dict["firstname"] as? String{
name = value
}
if let value = dict["rollnumber"] as? Int{
number = value
}
}
}
答案 1 :(得分:0)
会是这样的:
struct User: Decodable {
let name: String
let number: Int
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: UserKeys.self)
name = try container.decode(String.self, forKey: .name)
number = try container.decode(Int.self, forKey: .number)
}
private enum UserKeys: String, CodingKey {
case name = "firstname"
case number = "rollnumber"
}
static getUser(jsonData: Data) -> User? {
do {
let user = try JSONDecoder().decode(User.self, from:jsonData)
return user
} catch {
return nil
}
}
}
并获取用户:
User.getUser(jsonData: data)