我有一个要存储的用户个人资料,结构像这样
struct Profile: Codable {
let company: String?
let country: String?
let createdDate: String?
let dateOfBirth: String?
let department: String?
let email: String?
let employeeKey: String?
let firstName: String?
let gender: String?
let id: String?
let jobTitle: String?
let lastName: String?
let location: String?
let mobileDeviceToken: String?
let pictureUri: String?
let roles: [String]?
let status: String?
let updatedDate: String?
let userId: String?
let webDeviceToken: String?
let webMobileDeviceToken: String?
enum CodingKeys: String, CodingKey {
case company = "company"
case country = "country"
case createdDate = "createdDate"
case dateOfBirth = "dateOfBirth"
case department = "department"
case email = "email"
case employeeKey = "employeeKey"
case firstName = "firstName"
case gender = "gender"
case id = "id"
case jobTitle = "jobTitle"
case lastName = "lastName"
case location = "location"
case mobileDeviceToken = "mobileDeviceToken"
case pictureUri = "pictureUri"
case roles = "roles"
case status = "status"
case updatedDate = "updatedDate"
case userId = "userId"
case webDeviceToken = "webDeviceToken"
case webMobileDeviceToken = "webMobileDeviceToken"
}
}
我还有另一个看起来像的结构
struct ArticleAuthor {
let name: String
let department: String
let email: String
}
获取用户个人资料时,我希望能够使用从我的个人资料服务返回的个人资料对象创建ArticleAuthor结构。
我希望做这样的事情,但是由于from值应该是数据,所以它不起作用。
self?.profileService.fetchForUserByUserId(userId: authorId) { [weak self] profile, error in
guard error == nil else { return }
let author = try? JSONDecoder().decode(ArticleAuthor.self, from: profile)
print(author) // should be a populated author property
}
我希望避免使用let author = ArticleAuthor(name: profile?.firstName, department: profile?.department, email: profile?.email)
之类的东西,因为该对象可能会随着时间增长。
答案 0 :(得分:2)
示例代码中的配置文件对象已被“解码”,因此您无需再次对其进行解码。
为避免使用默认的init,只需添加一个自定义的初始化程序,以便可以传入Profile结构并设置值。通常,这是最好的解决方法,因为当您添加新属性时,它可以防止在整个代码库中进行大量更改
struct ArticleAuthor {
let name: String?
let department: String?
let email: String?
init(profile: Profile) {
self.name = profile.firstName
self.department = profile.department
self.email = profile.email
}
}
self?.profileService.fetchForUserByUserId(userId: authorId) { [weak self] profile, error in
guard error == nil else { return }
let author = Author(profile: profile)
print(author) // should be a populated author property
}