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

How can I init a struct from the values of a different struct

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

的结构
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) 这样的事情,因为这个对象会随着时间的推移而增长。

您的示例代码中的配置文件对象已经是'Decoded',因此您无需再次对其进行解码。

为了避免使用默认的初始化,你可以只添加一个自定义的初始化器,这样你就可以传入一个配置文件结构并设置值。这通常是最好的解决方法,因为它可以防止在添加新属性时对整个代码库进行大量更改

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
}