ios - 从 Swift1.2 迁移到 Swift 2 时出错 : "value of type "UIViewController"has no member 'className'

标签 ios swift swift2

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

value of type "UIViewController" has no member '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 的等价物吗? 感谢您的帮助。

最佳答案

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

因此,最好的解决方案不是寻找 className 的替代方案,而是使用更好、更“swift ”的方式——类似于

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
}

关于ios - 从 Swift1.2 迁移到 Swift 2 时出错 : "value of type "UIViewController"has no member 'className' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34375989/

相关文章:

ios - 如何在 UITableView 底部添加 UIRefreshControl?

ios - "try?"和 AVAudioPlayer 问题

iphone - 在 Objective-C 中选择一个随机枚举

ios - Flutter:Runner.app/Info.plist 不存在。 Flutter "Thin Binary"构建阶段必须在 "Copy Bundle Resources"之后运行

ios - 带有静态链接的 libz dylib 不支持 iOS 7

ios - 如何在 Swift 中将类名指定为变量?

swift - Swift 2.0协议(protocol)扩展和Java/C#抽象类之间有区别吗?

ios - 有没有办法在运行时检测 iOS 上的 VFP/NEON/Thumb/...?

ios - 核心数据警告 : Unrecognized optimized model archive format

ios - 如何在 ios swift 的整个应用程序中打开音频播放器 View ?