问题
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
}
}
encode to User Object
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
}
My question is how can i modify above object values and also it's a var type
when i tried
userInfo.firstName = "something other"
print(userInfo.firstName)// output: Vishal
Again same result
also tried with mutating func
userInfo.update(firstName: "something other")
print(userInfo.firstName) // output: Vishal
Not able to modify existing values.
回答1:
Change let to var when declaring userInfo;
if var userInfo = responseModel.responseBody {
// get userInfo object
userInfo.firstName = "something other"
print(userInfo.firstName)
}
来源:https://stackoverflow.com/questions/48375826/not-able-to-modify-codable-class-properties