ios - Swift 中基于之前 View Controller 的 If 语句

标签 ios objective-c swift uiviewcontroller

<分区>

我一直在尝试将此代码从 Obj-C 转换为 Swift:If statement based on whatever the previous view controller was (几乎完全相同的问题)

换句话说,我想返回到用户来自的 View Controller,MainViewController 或 SearchTableViewController 在两个展开 segue 之间进行选择。

我的问题是:如何使用 Swift 而不是 Obj-c 编写与上面链接中相同的功能代码?

这是我目前的翻译(不工作,无法消除错误)

//Method
func backViewController() -> UIViewController {
        let numberOfViewControllers = self.navigationController!.viewControllers.count
        if numberOfViewControllers < 2 {
            return nil
        }
        else {
            return self.navigationController!.viewControllers[numberOfViewControllers - 2]
        }
    }


    if  self.backViewController() == MainViewController {
//Back to MainViewController
        self.performSegueWithIdentifier("AuthorBackMain", sender: self)
    }
    else {
//Back to SearchTableViewController
        self.performSegueWithIdentifier("AuthorBackSearch", sender: self)
    }

编辑/进度:

我已将函数更改为 backViewController() -> UIViewController? 并消除了那里的错误。但是在 if 语句中出现了一个新的错误,关于二元运算符 '=='

"Binary operator '==' cannot be applied to operands of type 'UIViewController?' and 'MainViewController.Type'.

最佳答案

这是 swift 。只有 Optional 可以是 nil。您正在尝试从 backViewController 方法返回 UIViewController。 UIViewController 不是 Optional,因此它不能为 nil。如果您需要它为 nil,请将其设置为 Optional: UIViewController?

关于ios - Swift 中基于之前 View Controller 的 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39090855/

相关文章:

ios - 使用[ self 释放]、[ self 保留]是个好方法吗?

ios - 当我将 Charts UIView 作为 IBOutlet 添加到 ViewController 时,应用程序崩溃

ios - 如何设置按钮的标题颜色?

ios - 在临时分发中加载自定义框架时出错

swift - 数组超出范围 - Swift

ios - 向 NSAttributedString 添加常规操作?

ios - iOS 7 中的导航栏裁剪背景图像;ClipsToBounds :NO not working

ios - UICollectionView 图片加载问题

objective-c - 带有部分的 iOS GridView

swift - swift 将 uint32 值拆分为 uint8 值