1

So I have been having fun with default parameter values.

class containerViewController: UIViewController {
    var detailView:UIViewController?

    override func viewDidLoad(){
        super.viewDidLoad()
        detailView = anotherViewController()
    }

    func hideDetailView(vc:UIViewController? = detailView){ // <- THIS LINE
        // code
    }
}

The line Ive marked produces an error:

'containerViewController.Type' does not have a member named 'detailView'

Ive been reading online, including this question, but I cant seem to figure out how to fix this.

What I want is to be able to use hideDetailView() and if I send in a specific view controller as a parameter to that function, it hides that specific view controller. If I dont send any parameter, it just hides the current view controller that is held in the detailView parameter.

How can I achieve this?

Community
  • 1
  • 1
Jimmery
  • 9,783
  • 25
  • 83
  • 157

1 Answers1

2

You can use nil for the default value, and check if nil in the body.

func hideDetailView(vc:UIViewController? = nil){ // <- THIS LINE
    let vc_ = vc ?? detailView
    // code
}

But In this case, you can't distinguish following calls:

// passing `nil` as Optional<UIViewController>
let vc:UIViewController? = nil
container.hideDetailView(vc: vc)

// use default value
container.hideDetailView()

If you don't like that, you can use UIViewController??:

func hideDetailView(vc:UIViewController?? = nil){
    let vc_ /*: UIViewController? */ = vc ?? detailView 
    // code
}
rintaro
  • 51,423
  • 14
  • 131
  • 139