1

How do you do optional binding on an optional of optional?

For example, assume UIViewController's navigationController property is an optional of optional. Should I use method #1 or method #2, or is there a third way?

Method #1

if let navigationController = viewController.navigationController! {

}

or

Method #2

if let optionalNavigationController = viewController.navigationController {
   let navigationController = optionalNavigationController {

    }
}
Boon
  • 40,656
  • 60
  • 209
  • 315
  • Related: [How to unwrap Optional> in Swift 1.2](http://stackoverflow.com/questions/28724946/how-to-unwrap-optionaloptionalt-in-swift-1-2). – Martin R Aug 06 '15 at 12:17

4 Answers4

1

There is another solution:

if let stillOptional = viewController.navigationController, let notOptional = stillOptional {
    //use notOptional here
}
Dániel Nagy
  • 11,815
  • 9
  • 50
  • 58
0
if let navigationController = viewController?.navigationController
oisdk
  • 9,763
  • 4
  • 18
  • 36
0

Much more functional-programming solution:

if let a = optionalOfOptional?.map({$0}) {
    println(a)
}
rshev
  • 4,086
  • 1
  • 23
  • 32
0

If you know that the view controller has a navigation controller, because you designed it in Interface Builder or created it programmatically, declare a variable

var navigationController : UINavigationController!

and assign the navigation controller in viewDidLoad() as implicit unwrapped optional

navigationController = viewController!.navigationController!

If you don't know, use a normal optional binding as described in the other answers

vadian
  • 274,689
  • 30
  • 353
  • 361