Im using Swift 3
Wondering whether any method is available to check if all the properties in an object has value / nil
Eg:
class Vehicle {
var name : String?
var model: String?
var VIN: String?
}
let objCar = Vehicle()
objCar.name = "Volvo"
if objCar.{anyProperty} ! = nil {
//Go to other screen
}
Im in search of the {anyProperty} method where it returns true only if I have values for all properties of objCar. In our case, objCar has no model and VIN and so {anyProperty} is false and will come out of if loop
Pls advice
I'm not sure if this should be used for production apps, as I'm not very familiar with reflection in Swift (using
Mirror
) and if it has any negative aspects (performance, etc).Here goes:
hasMissingValues
will be false in the above example (all properties ofVehicle
are set). Comment the line wheremodel
is set, for example, and the value ofhasMissingValues
will now be true.Note: There may be a better way to compare
$0.value
(of typeAny
) to nil. Also, this works for properties of any type (not justString
) of the class.I would strongly recommend against this. State validation is something which should happen from inside a class. From inside the class, you should know better how to check validity.
If there are subclasses with different rules for
isReadyToAdvance()
they can override that method.If
isReadyToAdvance()
doesn't make sense for the base class, then add it as an extension.@iPeter asked for something a bit more compact when there are lots of properties.
If you have a lot of fields, you can use this approach: