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

后端 未结 3 2120
情深已故
情深已故 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:00

    If you have a lot of fields, you can use this approach:

    struct S {
        let x: String?
        let y: Int
        let z: Bool
    
        func hasNilField() -> Bool {
            return ([x, y, z] as [Any?]).contains(where: { $0 == nil})
        }
    }
    

提交回复
热议问题