无法分配类型的值' UIViewController'键入' UITabBarController?'

时间:2016-03-17 06:48:44

标签: swift compiler-errors type-safety

我正在尝试从标识符中实例化UITabBarController,但是遇到以下错误:

Cannot assign value of type 'UIViewController' to type 'UITabBarController'

以下是违规代码:

if NSUserDefaults.standardUserDefaults().boolForKey("LoginPage") == true
    {
        tabBarController = k_Storyboard.instantiateViewControllerWithIdentifier("TabbarController")  //------Error Showed in this Line.
        self.window!.rootViewController = tabBarController
        UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState: .Selected)
        UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor(red: 246 / 255.0, green: 206 / 255.0, blue: 206 / 255.0, alpha: 1.0)], forState: .Normal)
        isFirstPage = true
    }

1 个答案:

答案 0 :(得分:2)

回答:您正在尝试从UIViewController类型到子类UITabBarController的隐式向下转发。编译器是阻止你这样做的正确方法。您必须明确尝试通过更改

来强制转发

k_Storyboard.instantiateViewControllerWithIdentifier("TabbarController")

以下内容:

k_Storyboard.instantiateViewControllerWithIdentifier("TabbarController") as! UITabBarController

如果您仍然不理解错误,请以这种方式考虑:编译器无法保证从UIViewController返回的instantiateViewControllerWithIdentifierUITabBarController。您必须明确保证它。