-3

I am looking at the code to implement the pageviewcontroller and I don't understand this line of code:

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

What does ?? mean?

It was used in this context:

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]
}
Rob
  • 415,655
  • 72
  • 787
  • 1,044
alvin123
  • 79
  • 2
  • 8
  • 1
    check Nil-Coalescing Operator https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html – ArunGJ Feb 03 '18 at 17:43

1 Answers1

0

On its left side there is an expression that evaluates to optional (a value or a nil), on it's right side you provide a default value that is used if the left side is evaluated to nil.

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

In your example, subViewController.index(of: viewController) is the left side that evaluates to optional integer - Int?. However, to make sure you won't have to deal with optional value, on the right side you provide a default value '0'. Thanks to that currentIndex will always have a value.

If you are familiar with ternary operator, it's intepreted as:

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

Or in if-else syntax:

let currentIndex: Int
if subViewController.index(of: viewController) != nil {
    currentIndex = subViewController.index(of: viewController)!
} else {
    currentIndex = 0
}
Milan Nosáľ
  • 19,169
  • 4
  • 55
  • 90