无法修改Codable类属性?

时间:2018-01-22 06:34:30

标签: swift properties codable

Swift开发的新功能。我的USER JSON有一个类结构。我能够将JSON值编码为User对象,但是当我想要修改这些属性时,更改不会反映在类结构中。你能帮我吗?

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类型

当我尝试

userInfo.firstName = "something other"
print(userInfo.firstName)// output: Vishal

同样的结果

还尝试使用mutating func

userInfo.update(firstName: "something other")
print(userInfo.firstName) // output: Vishal

无法修改现有值。

1 个答案:

答案 0 :(得分:-1)

在声明userInfo时将let更改为var;

if var userInfo = responseModel.responseBody {
  // get userInfo object
  userInfo.firstName = "something other"
  print(userInfo.firstName)
 }