I have model as below.
struc Info: Decodable {
var firstName: String?
var lastName: String?
}
While displaying in tableview cell, w
I would recommend one of two options:
Personally, I like option 1. I think it's the most compact and also the easiest to maintain.
Option 1 Example:
struct Info1: Decodable {
var firstName: String?
var lastName: String?
var displayName: String {
return [self.firstName, self.lastName]
.compactMap { $0 } // Ignore 'nil'
.joined(separator: " ") // Combine with a space
}
}
print(Info1(firstName: "John", lastName: "Smith").displayName)
// Output: "John Smith"
print(Info1(firstName: "John", lastName: nil).displayName)
// Output: "John"
print(Info1(firstName: nil, lastName: "Smith").displayName)
// Output: "Smith"
print(Info1(firstName: nil, lastName: nil).displayName)
// Output: ""
Option 2 Example:
struct Info2: Decodable {
var firstName: String
var lastName: String
enum CodingKeys: String, CodingKey {
case firstName, lastName
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.firstName = try container.decodeIfPresent(String.self, forKey: .firstName) ?? ""
self.lastName = try container.decodeIfPresent(String.self, forKey: .lastName) ?? ""
}
// Optional:
var displayName: String {
return [self.firstName, self.lastName]
.compactMap { $0.isEmpty ? nil : $0 } // Ignore empty strings
.joined(separator: " ") // Combine with a space
}
// TEST:
init(from dict: [String: Any]) {
let data = try! JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
self = try! JSONDecoder().decode(Info2.self, from: data)
}
}
print(Info2(from: ["firstName": "John", "lastName": "Smith"]).displayName)
// Output: "John Smith"
print(Info2(from: ["lastName": "Smith"]).displayName)
// Output: "Smith"
print(Info2(from: ["firstName": "John"]).displayName)
// Output: "John"
print(Info2(from: [String: Any]()).displayName)
// Output: ""