Swift - 正确使用AnyObject

时间:2015-08-05 09:31:18

标签: ios iphone swift ios7 ios8

我是swift的新手。我正在使用storyboard并根据登录信息,我正在更改UIViewController以加载。以下是摘录。

class func viewControllerWithName(name: String) -> UIViewController?
    {
        let storyboard = mainStoryboard()
        let viewController: AnyObject! = storyboard.instantiateViewControllerWithIdentifier(name)
        return viewController as? UIViewController
    }

func setUpController {
        let viewController: AnyObject!
        if self.user() == "admin" {
            viewController:AdminViewController = self.viewControllerWithName("admin") !as! AdminViewController
        } else {
            viewController:UserViewController = self.viewControllerWithName("user") !as! UserViewController
        }
        self.addChildViewController(viewController)
        viewController.view.frame = container.frame
        self.view.addSubview(viewController.view)
        viewController.didMoveToParentViewController(self)
    }

我尝试了很多方法,但是,我无法对viewController进行类型转换。我收到错误,说

Cannot invoke 'addChildViewController' with an argument list of type '(AnyObject!)'

实现这一目标的正确格式是什么?

3 个答案:

答案 0 :(得分:1)

当你知道它将成为一个视图控制器时,为什么要将它声明为AnyObject?将其声明为UIViewController,您提到的错误应该消失。

您不需要在if-else部分执行viewController:AdminViewController。无论如何,你强制对viewControllerWithName方法的输出进行类型转换。

答案 1 :(得分:0)

在这种情况下,您指示viewController是AnyObject类型:

let viewController: AnyObject!

要将UIVIewController传递给addChildViewController,您可以尝试以下方法:

let viewController = self.viewControllerWithName("admin") as! AdminViewController

self.addChildViewController(viewController)

在swift中,您无法在运行时更改let或var类型

答案 2 :(得分:0)

更新代码并将AnyObject更改为UIViewController:

class func viewControllerWithName(name: String) -> UIViewController?
    {
        let storyboard = mainStoryboard()
        let viewController = storyboard.instantiateViewControllerWithIdentifier(name) as? UIViewController
        return viewController 
    }

func setUpController {
        let viewController: UIViewController!
        if self.user() == "admin" {
            viewController = self.viewControllerWithName("admin")!
        } else {
            viewController = self.viewControllerWithName("user")! 
        }
        self.addChildViewController(viewController)
        viewController.view.frame = container.frame
        self.view.addSubview(viewController.view)
        viewController.didMoveToParentViewController(self)
    }