Swift2运行时实例化UIStoryboard,失败如何处理?

Instantiate UIStoryboard at runtime in Swift2, how to handle failure?

我正在尝试根据应用程序中的某些运行时条件动态加载 UIStoryboard(然后在其中实例化视图控制器)

因为方法 UIStoryboard(name: bundle:) 完全看起来可能会失败(即错误的文件名,在包中找不到等)我假设它 return 是一个可选的输入 UIStoryboard?。然而,写这段代码:

if let storyboard = UIStoryboard(name: "", bundle: nil) as? UIStoryboard{
    // Use the storyboard...   
}

...发出警告:

Conditional cast from 'UIStoryboard' to 'UIStoryboard' always succeeds

因为它是一个初始值设定项,内联文档中的方法签名(选择并单击方法的 name: 标签)没有列出 return 类型。

文档的实际网页(预发布,here)说:

Return Value

A storyboard object for the specified file. If no storyboard resource file matching name exists, an exception is thrown with description: Could not find a storyboard named 'XXXXXX' in bundle....

(强调我的)。然而,尝试 do-try-catch 方法给了我警告:

No calls to throwing functions occur within 'try' expression

那么,我该如何处理失败?

我认为Apple 不会处理它。如果你想获取主故事板,但你不知道它的名字,你可以试试这个代码。

if let mainDict = NSBundle.mainBundle().infoDictionary {
    if let storyboardName = mainDict["UIMainStoryboardFile"] as? String {
         let mainStoryBoard = UIStoryboard(name: storyboardName, bundle: nil)
    }
}

希望对您有所帮助!

我们也可以有一个扩展程序做同样的事情 (Swift 2.0)

public extension UIViewController {

    public class func createInstanceFromStoryboardName(storyboardName: String, storyboardId: String) -> UIViewController? {
        let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
        let instance = storyboard.instantiateViewControllerWithIdentifier(storyboardId) as? UIViewController
        return instance
    }
}

那么在你class

if let myViewController  = UIViewController.createInstanceFromStoryboardName("UIMainStoryboardFile", storyboardId: "ID_MYVIEWCONTROLLER") as? myViewController {
// Todo
}