如何在不知道此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?
}
答案 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