检查结构中的任何属性是否为nil - Swift 4

时间:2018-01-21 18:42:34

标签: swift class struct swift4 optional

如何在不知道此struct属性的数量和类型的情况下检查struct的所有属性是否为零?

因此,您可能需要查看此struct

struct Fruit {
 var name: String?
 var fruitType: String?
 var quantity: Int?
}

以及后来的另一个struct,例如:

struct Farm {
 var name: String?
 var isOpen: Bool?
 var farmerName: String?
 var location: Location?
 var isCertified: Bool?
}

1 个答案:

答案 0 :(得分:0)

protocol StructExt {
    func allPropertiesAreNotNull() throws -> Bool
}

extension StructExt {
    func allPropertiesAreNotNull() throws -> Bool {

        let mirror = Mirror(reflecting: self)

        return !mirror.children.contains(where: { $0.value as Any? == nil})
    }
}

现在测试两种结构应该如下:

var fruit = Fruit() // Assuming with have an initializer for the struct
var farm = Farm() // Assuming with have an initializer for the struct
fruit.allPropertiesAreNotNull() // will return true or false depending on weither or not there is a nil property in that struct
farm.allPropertiesAreNotNull() // will return true or false depending on weither or not there is a nil property in that struct