ios - 检查两个对象在 Swift 中是否为 nil,ios xcode

标签 ios xcode swift

我想比较两个对象(属于同一类)并返回不为零的对象。

你如何在 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/

相关文章:

ios - DataSource Pattern 与 UITableView 一起使用是依赖注入(inject)的示例吗?

iphone - iCloud:KeyValue 存储还是文档存储?

ios - 按特定字符拆分字符串,iOS

ios - iOS UIActivityViewController 取消按钮中缺少文本

ios - UICollectionView - 当键盘出现时,整个 Collection View 随键盘移动

ios - MergeSwiftModule - 在 Xcode 6.3 中构建 Swift 应用程序卡在 "Merge MyApp.swiftmodule"

objective-c - 我如何在 Objective C 中表示当前的 JSON 方案?

c++ - 是否可以在 Xcode 的 C++ 项目中包含框架?

swift - 使用 NSLocalNotification 进行多次提醒

c - Swift:无法将函数指针转换为 (void*) 以便在 C 风格的第三方库中使用