0

How to check that all properties of a struct are not nil, without knowing the number and types of the properties of this struct?

So, you may want to check this struct:

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

and later another struct such as this one:

struct Farm {
 var name: String?
 var isOpen: Bool?
 var farmerName: String?
 var location: Location?
 var isCertified: Bool?
}
Stephane Paquet
  • 2,315
  • 27
  • 31

1 Answers1

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})
    }
}

Now testing for both structs should be done the following:

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
Stephane Paquet
  • 2,315
  • 27
  • 31