how to handle the nil value variables

后端 未结 1 1749
不知归路
不知归路 2021-01-17 02:51

I have model as below.

struc Info: Decodable {
    var firstName: String?
    var lastName: String?
}

While displaying in tableview cell, w

1条回答
  •  有刺的猬
    2021-01-17 03:14

    I would recommend one of two options:

    1. Add computed property to the struct to determine the display name.
    2. Manually decode, providing default values. (And also add a display name property if you want)

    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: ""
    

    0 讨论(0)
提交回复
热议问题