Jac*_*ack 3 class optional swift
我使用Swift 3
想知道是否有任何方法可用于检查对象中的所有属性是否具有值/ 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
}
Run Code Online (Sandbox Code Playgroud)
我正在寻找{anyProperty}方法,只有当我拥有objCar的所有属性的值时,它返回true.在我们的例子中,objCar没有模型和VIN,所以{anyProperty}是假的,并且将来自if循环
请咨询
我不确定这是否应该用于生产应用程序,因为我不太熟悉Swift中的反射(使用Mirror)以及它是否有任何负面影响(性能等).
开始:
class Vehicle {
var name : String?
var model: String?
var VIN: String?
}
let objCar = Vehicle()
objCar.name = "Volvo"
objCar.model = "242DL"
objCar.VIN = "123456"
let hasMissingValues = Mirror(reflecting: objCar).children.contains(where: {
if case Optional<Any>.some(_) = $0.value {
return false
} else {
return true
}
})
print(hasMissingValues)
Run Code Online (Sandbox Code Playgroud)
hasMissingValues在上面的例子中将是false(Vehicle设置的所有属性).model例如,注释设置的行,hasMissingValues现在的值将为true.
注意:可能有更好的方法来比较$0.value(类型Any)和nil.此外,这适用于类的任何类型(不仅仅是String)的属性.
我强烈建议不要这样做.状态验证是应该从类内部发生的事情.从课堂内部,您应该更好地了解如何检查有效性.
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
}
Run Code Online (Sandbox Code Playgroud)
如果存在具有不同规则的子类,则isReadyToAdvance()它们可以覆盖该方法.
如果isReadyToAdvance()对基类没有意义,则将其添加为扩展名.
extension Vehicle {
func isReadyToAdvance() -> Bool {
return name != nil && model != nil && VIN != nil
}
}
Run Code Online (Sandbox Code Playgroud)
当有很多属性时,@ iPeter要求更紧凑的东西.
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
}
}
Run Code Online (Sandbox Code Playgroud)
如果你有很多字段,你可以使用这种方法:
struct S {
let x: String?
let y: Int
let z: Bool
func hasNilField() -> Bool {
return ([x, y, z] as [Any?]).contains(where: { $0 == nil})
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3102 次 |
| 最近记录: |