【问题标题】:What does ?? mean? [duplicate]有什么作用??意思是? [复制]
【发布时间】:2018-02-03 17:41:01
【问题描述】:

我在看实现pageviewcontroller的代码,这行代码看不懂:

let currentIndex: Int = subViewController.index(of: viewController) ?? 0

?? 是什么意思?

在这种情况下使用它:

func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
    let currentIndex: Int = subViewController.index(of: viewController) ?? 0
    if currentIndex <= 0 {
        return nil
    }
    return subViewController[currentIndex - 1]
}

【问题讨论】:

标签: ios swift


【解决方案1】:

在其左侧有一个计算结果为可选(值或 nil)的表达式,在其右侧,您提供了一个默认值,如果左侧计算为 nil,则使用该值。

let currentIndex: Int = subViewController.index(of: viewController) ?? 0

在您的示例中,subViewController.index(of: viewController) 是计算结果为可选整数的左侧 - Int?。但是,为了确保您不必处理可选值,请在右侧提供默认值“0”。多亏了currentIndex 总是有一个价值。

如果你熟悉三元运算符,它的解释是:

let currentIndex: Int = subViewController.index(of: viewController) != nil ? subViewController.index(of: viewController)! : 0

或if-else 语法:

let currentIndex: Int
if subViewController.index(of: viewController) != nil {
    currentIndex = subViewController.index(of: viewController)!
} else {
    currentIndex = 0
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-09
    • 2011-05-10
    • 2021-08-29
    • 1970-01-01
    • 2019-09-12
    • 2015-01-22
    • 2020-10-27
    • 2015-07-15
    相关资源
    最近更新 更多