0

I have just started translating my app to Swift, I want the CBCentralManager.delegate to be set to another view controller(One that navigation controller pushes onto).

I am trying to do the same with following code:

let viewCont = self.storyboard!.instantiateViewControllerWithIdentifier("mainView")
self.navigationController?.pushViewController(viewCont, animated: true)
manager.delegate = viewCont

The variable manager is an instance of CBCentralManager and setting delegate to viewCont raises following error:

"Cannot assign value of type 'UIViewController' to type 'CBCentralManagerDelegate?'"

The declaration for the view Controller:

class MainViewController: UIViewController, CBCentralManagerDelegate

How can I solve the same?

Aakash Thakkar
  • 301
  • 1
  • 3
  • 20
  • Why do you need that? If you want that delegate methods to be called in your another viewcontroller, then declare CBCentralManager and initialise there. – rushisangani Feb 24 '16 at 12:58

1 Answers1

2

You need to downcast the view controller you receive from instantiateViewControllerWithIdentifier. Without the downcast, all the compiler knows is that you have a UIViewController

let viewCont = self.storyboard!.instantiateViewControllerWithIdentifier("mainView") as! MainViewController
self.navigationController?.pushViewController(viewCont, animated: true)
manager.delegate = viewCont

Once you have the downcast using as! then the compiler knows that it has a MainViewController and since this class is also a CBCentralManagerDelegate it is happy.

Paulw11
  • 108,386
  • 14
  • 159
  • 186