我有一个用户配置文件,我用一个形状像这样的结构存储
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)
因为这个物体会随着时间的推移而增长。