我想比较两个对象(属于同一类)并返回不为零的对象。
你如何在 swift 中写出这样的东西? :
func returnWhatIsNotNil(objA: SomeClass, objB: SomeClass) -> SomeClass {
if objA != nil && objB != nil { //error
//both are not nil
return nil
}
if objA == nil && objB != nil { // error
// objA is nil
return objB
}
if objA != nil && objB == nil { // error
// objB is nil
return objA
}
}
只有一个对象,
if let x = objA {
//objA is not nil
}
会完成这项工作,但我不知道如何用两个对象完成这项工作。
最佳答案
class SomeObject {
}
func returnWhatIsNotNil(objA: SomeObject?, objB: SomeObject?) -> SomeObject? {
if let objA = objA where objB == nil {
return objA
}
if let objB = objB where objA == nil {
return objB
}
return nil
}
关于ios - 检查两个对象在 Swift 中是否为 nil,ios xcode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30624946/