gpt4 book ai didi

swift - 在 Swift 中返回实例类型

转载 作者:IT王子 更新时间:2023-10-29 05:02:37 24 4
gpt4 key购买 nike

我正在尝试进行此扩展:

extension UIViewController
{
class func initialize(storyboardName: String, storyboardId: String) -> Self
{
let storyboad = UIStoryboard(name: storyboardName, bundle: nil)
let controller = storyboad.instantiateViewControllerWithIdentifier(storyboardId) as! Self

return controller
}
}

但是我得到了编译错误:

error: cannot convert return expression of type 'UIViewController' to return type 'Self'

这可能吗?我也想把它变成 init(storyboardName: String, storyboardId: String)

最佳答案

类似于Using 'self' in class extension functions in Swift ,你可以定义一个通用的辅助方法,它从调用上下文中推断出 self 的类型:

extension UIViewController
{
class func instantiateFromStoryboard(storyboardName: String, storyboardId: String) -> Self
{
return instantiateFromStoryboardHelper(storyboardName, storyboardId: storyboardId)
}

private class func instantiateFromStoryboardHelper<T>(storyboardName: String, storyboardId: String) -> T
{
let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
let controller = storyboard.instantiateViewControllerWithIdentifier(storyboardId) as! T
return controller
}
}

然后

let vc = MyViewController.instantiateFromStoryboard("name", storyboardId: "id")

编译,类型被推断为MyViewController


Swift 3 的更新:

extension UIViewController
{
class func instantiateFromStoryboard(storyboardName: String, storyboardId: String) -> Self
{
return instantiateFromStoryboardHelper(storyboardName: storyboardName, storyboardId: storyboardId)
}

private class func instantiateFromStoryboardHelper<T>(storyboardName: String, storyboardId: String) -> T
{
let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: storyboardId) as! T
return controller
}
}

另一种可能的解决方案,使用 unsafeDowncast:

extension UIViewController
{
class func instantiateFromStoryboard(storyboardName: String, storyboardId: String) -> Self
{
let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: storyboardId)
return unsafeDowncast(controller, to: self)
}
}

关于swift - 在 Swift 中返回实例类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33200035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com