类在swift中动态地转换 [英] Class casting dynamically in swift

查看:140
本文介绍了类在swift中动态地转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图以dyanmically方式投射到Swift中的一个类。这可能吗?这里是我试图使用的代码:

I am trying to dyanmically cast to a class in Swift. Is this possible? Here is the code I am trying to use:

let stringClass: AnyClass = NSString.self
let anyObject: AnyObject = "foo"
let string = anyObject as! stringClass

代码无法在转换中编译。这是可能的,如果是,为什么是正确的语法?

The code fails to compile at the cast. Is this possible and if so, why is the right syntax?

问题。我试图重构此代码:

Here is the real issue. I am attempting to refactor this code:

switch (value) {
    case "valueOne":
        viewController = storyboard.instantiateViewController(withIdentifier: "foo") as! FirstViewController
    case "valueTwo":
        viewController = storyboard.instantiateViewController(withIdentifier: "bar") as! SecondViewController
    default:
        return nil
}

into: / p>

into:

let controllersDictionary: [String: (String, UIViewController.Type)] = [
    "valueOne" : ("bar", FirstViewController.self),
    "valueTwo" : ("foo", SecondViewController.self)
]
let tuple = controllersDictionary[value]!
let identifier = tuple.0
let cast = tuple.1
let viewController = storyboard.instantiateViewController(withIdentifier: identifier) as! cast


推荐答案

点是为。您可以写:

let controllersDictionary: [String: String] = [
    "valueOne" : "bar",
    "valueTwo" : "foo"
]
let identifier = controllersDictionary[value]!
let viewController = storyboard.instantiateViewController(withIdentifier: identifier)

在您显示的代码。 viewController 被键入为UIViewController,但是它是正确的基础视图控制器子类感谢多态性;无论类是在故事板中,这是这个实例的类。

The cast does nothing for you in the code that you have shown. viewController is typed as UIViewController, but it is the correct underlying view controller subclass thanks to polymorphism; whatever the class is in the storyboard, that's the class of this instance.

只有当你需要消息一个实例的消息属性只有子类,你在代码中没有显示出任何这样的需要。

The only time you need to cast down is when you have to message an instance with a message belonging only to the subclass, and you have not shown any such need at this point in your code.

这篇关于类在swift中动态地转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆