无法修改可编码类属性? [英] Not able to modify Codable Class Properties?
本文介绍了无法修改可编码类属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Swift开发的新功能。我的USER JSON有一个类结构。我能够将JSON值编码为User对象,但是当我想要修改这些属性时,更改不会反映在类结构中。
New in Swift development. I have a class structure for my USER JSON. I am able to encode JSON value to User object but when I want to modify these properties changes not reflected in a class structure. Can you please help me.
import Foundation
struct UserInfo : Codable {
let userId : String?
var firstName : String?
var lastName : String?
let email : String?
let phone : String?
enum CodingKeys: String, CodingKey {
case userId = "userId"
case firstName = "firstName"
case lastName = "lastName"
case email = "email"
case phone = "phone"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
userId = try values.decodeIfPresent(String.self, forKey: .userId)
firstName = try values.decodeIfPresent(String.self, forKey: .firstName)
lastName = try values.decodeIfPresent(String.self, forKey: .lastName)
email = try values.decodeIfPresent(String.self, forKey: .email)
phone = try values.decodeIfPresent(String.self, forKey: .phone)
}
//trying with mutating function but not able to modify
mutating func update(firstName fName: String) {
self.firstName = fName
}
mutating func update(email newMail: String) {
self.email = newMail
}
}
编码为用户对象
let jsonDecoder = JSONDecoder()
let responseModel = try jsonDecoder.decode(LoginResponseBody.self, from: data)
if let userInfo = responseModel.responseBody {
// get userInfo object
print(userInfo.firstName) // output: Vishal
}
我的问题是,如何修改上面的对象值,而且还是var类型?
My question is how can i modify above object values and also it's a var type
我尝试过
userInfo.firstName = "something other"
print(userInfo.firstName)// output: Vishal
再次获得相同的结果
也尝试了对func进行突变
also tried with mutating func
userInfo.update(firstName: "something other")
print(userInfo.firstName) // output: Vishal
无法修改现有值。
推荐答案
在以下情况下将其更改为var声明userInfo;
Change let to var when declaring userInfo;
if var userInfo = responseModel.responseBody {
// get userInfo object
userInfo.firstName = "something other"
print(userInfo.firstName)
}
这篇关于无法修改可编码类属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文