如何从不同结构的值初始化结构



我有一个用户配置文件,我正在存储一个形状

像的结构
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)这样的事情,因为这个物体可以随着时间的推移而增长。

示例代码中的配置文件对象已"解码",因此无需再次解码。

若要避免使用默认的 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
}

相关内容

  • 没有找到相关文章

最新更新