Reputation: 870
I have a model for a user profile
struct Profile {
let bio: String?
let company: String
let createdDate: Date
let department: String
let email: String
let firstName: String
let coverImageURL: URL?
let jobTitle: String
let lastName: String
let location: String?
let name: String
let profileImageURL: URL?
let roles: [String]
let isActive: Bool
let updatedDate: Date?
let userID: String
}
I need to render a UITableView
and assign each of these items to a row.
As this model is a single item, I am unsure how to achieve this, I had considered using Mirror to iterate over the struct and map each value but that feels a little gross and I'd like to retain some form of control as to what is rendered.
How can I convert this model to a data type I can iterate over for a table view?
Upvotes: 0
Views: 36
Reputation: 16341
You could create a dictionary of the properties as keys and values like this and use the dictionary to iterate through the values.
struct Profile: Codable {
//...
func getProfileDictionary() throws -> [String: Any] {
let data = try JSONEncoder().encode(self)
return try JSONSerialization.jsonObject(with: data) as? [String: Any] ?? [:]
}
}
Iterating through the key, values in the dictionary.
do {
let dictionary = try profile.getProfileDictionary()
for (key, value) in dictionary {
print("\(key): \(value)")
}
} catch { print(error) }
Upvotes: 2