【问题标题】:Error when migrating from Swift1.2 to Swift 2 : "value of type "UIViewController" has no member 'className'从 Swift1.2 迁移到 Swift 2 时出错:““UIViewController”类型的值没有成员“className”
【发布时间】:2015-12-19 22:22:03
【问题描述】:

我刚刚将我的 Swift 1.2 代码迁移到 Swift 2 代码,我得到了错误

UIViewController”类型的值没有成员“className

在这一行:

if(childViewController.className=="myPhotoCalendar.GalleryController")

这是我的代码:

func initLeftMenuController()
{
    for childViewController in self.childViewControllers
    {
        if(childViewController.className=="myPhotoCalendar.GalleryController")
        {
            self.galleryController=childViewController as! GalleryController
        }
        if(childViewController.className=="myPhotoCalendar.TextsController")
        {
            self.textsController=childViewController as! TextsController
        }
        if(childViewController.className=="myPhotoCalendar.TemplatesController")
        {
            self.templatesController=childViewController as! TemplatesController
        }
        if(childViewController.className=="myPhotoCalendar.StylesController")
        {
            self.stylesController=childViewController as! StylesController
        }
        if(childViewController.className=="myPhotoCalendar.ObjektsController")
        {
            self.objektsController=childViewController as! ObjektsController
        }
    }
}

有人知道 Swift 2 中的 className 等价物吗? 感谢您的帮助。

【问题讨论】:

    标签: ios swift swift2


    【解决方案1】:

    检查类名的相似性根本不是一个好主意——改用if let。如果你改变一个班级的名字,你会怎么做?这可能无法通过重构来解决,并且应用程序将停止工作。

    因此,最好的解决方案不是为className 寻找替代方案,而是使用更好、更“迅速”的方式——比如

    if let ctrl = childViewController as? GalleryController {
        self.galleryController = ctrl
    } else if (...) {
        ...
    }
    

    或者使用 switch 语句(正如 Martin 所说)(我不知道这是可能的,直到查找它):

    switch childViewController {
    case let ctrl as GalleryController:
        self.galleryController = ctrl
    case let ctrl as SomeOtherClass:
        self.something = ctrl
    // more cases
    default:
        break
    }
    

    【讨论】:

    • ... 或 switch 语句。
    • @MartinR 不知道那个 - 学习新东西总是很高兴:)
    猜你喜欢
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    相关资源
    最近更新 更多