check if any property in an object is nil - Swift 3

后端 未结 3 2119
情深已故
情深已故 2021-01-06 16:24

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 {
v         


        
3条回答
  •  星月不相逢
    2021-01-06 17:14

    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.

    class Vehicle {
        var name: String?
        var model: String?
        var VIN: String?
    
        func isReadyToAdvance() -> Bool {
            return name != nil && model != nil && VIN != nil
        }
    }
    
    let objCar = Vehicle()
    objCar.name = "Volvo"
    
    if objCar.isReadyToAdvance() {
        // Go to other screen
    }
    

    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.

    extension Vehicle {
        func isReadyToAdvance() -> Bool {
            return name != nil && model != nil && VIN != nil
        }
    }
    

    @iPeter asked for something a bit more compact when there are lots of properties.

    extension Vehicle {
        func isReadyToAdvance() -> Bool {
            // Add all the optional properties to optionals
            let optionals: [Any?] = [name, model, VIN]
            if (optionals.contains{ $0 == nil }) { return false }
    
            // Any other checks
    
            return true
        }
    }
    

提交回复
热议问题