krishna patel
krishna patel

Reputation: 51

Downcast from 'UIViewController?' to 'UIViewController' only unwraps optionals; did you mean to use '!'?

I am using below code to set root view controller. But It is giving me error:

    let storyboard = UIStoryboard(name:"SignUp", bundle:nil)
    let viewController = storyboard.instantiateInitialViewController() as! UIViewController
    self.window!.rootViewController = viewController

I am getting error like Downcast from 'UIViewController?' to 'UIViewController' only unwraps optionals; did you mean to use '!'?

I think, It has to do with "as!", but it is introduced in new swift.

Does any one have idea ?

Upvotes: 2

Views: 2457

Answers (1)

Moriya
Moriya

Reputation: 7906

Two ways to do this I suppose

Safer one:

 let storyboard = UIStoryboard(name:"SignUp", bundle:nil)
 if let viewController = storyboard.instantiateInitialViewController(){
    self.window!.rootViewController = viewController
 }

edit: removed as? UIViewController

The one suggested by the compiler:

 let storyboard = UIStoryboard(name:"SignUp", bundle:nil)
 let viewController = storyboard.instantiateInitialViewController()!
 self.window!.rootViewController = viewController

Basically the compiler is just letting you know that the as! UIViewController in this code is basically just the same as using one !

Upvotes: 2

Related Questions