检查对象中的任何属性是否为nil-Swift 3 [英] check if any property in an object is nil - Swift 3

查看:402
本文介绍了检查对象中的任何属性是否为nil-Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Swift 3

Im using Swift 3

想知道是否有任何方法可以检查对象中的所有属性是否都具有值/nil

Wondering whether any method is available to check if all the properties in an object has value / nil

例如:

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
}

我正在寻找{anyProperty}方法,仅当我具有objCar的所有属性的值时,该方法才返回true.在我们的例子中,objCar没有模型和VIN,因此{anyProperty}为假,它将在if循环中消失

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

请咨询

推荐答案

我强烈建议不要这样做.状态验证是应该在类内部进行的.从班级内部,您应该更好地了解如何检查有效性.

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
}

如果对于isReadyToAdvance(),存在具有不同规则的子类,则它们可以覆盖该方法.

If there are subclasses with different rules for isReadyToAdvance() they can override that method.

如果isReadyToAdvance()对基类没有意义,则将其添加为扩展.

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在属性很多时要求更紧凑的东西.


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

这篇关于检查对象中的任何属性是否为nil-Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆