简体   繁体   English

如何在Swift中从Mirror对象的子对象创建类的实例

[英]How do I create an instance of a class from the child of a Mirror object in Swift

I am trying to understand why I am unable to create an instance of a class using a mirror in Swift. 我试图理解为什么我无法使用Swift中的镜像创建类的实例。 In the playground, everything seems fine until the very last line of code below. 在操场上,一切都很好,直到下面的最后一行代码为止。

So, here's the first example with the use of type(of:): 因此,这是使用type(of :)的第一个示例:

// First Example
var s = String( "Foo" ) // Playground Output: Foo
type(of: s) // Playground Output:  String.Type
var typeClone = type( of: s ).init() // Playground Output: "" (as expected)

Everything works as expected. 一切正常。 Now, when I try to do this same sort of thing with a child found in a mirror object, the playground complains: 现在,当我尝试对在镜子对象中发现的孩子做同样的事情时,操场上抱怨道:

// Second Example
class FooContainer {
   var s : String = "Foo"
}

var t = FooContainer()
var tMirror = Mirror( reflecting: t ) // Output: Mirror for FooContainer
tMirror.children.first! // Output: {some "s"}, value "Foo")

type( of: tMirror.children.first!.value ) // Output: String.Type
var typeClone2 = type( of: tMirror.children.first!.value ).init()

The line with "typeClone2" is the one that fails. 带有“ typeClone2”的行是失败的行。 If I break down the expressions and inspect things, it seems like all of the types and values are similar, as in the first example. 如果我分解表达式并检查事物,则似乎所有类型和值都相似,如第一个示例中所示。 But in the second case, the playground emits this error: 但是在第二种情况下,游乐场发出此错误:

Playground execution failed: 游乐场执行失败:

error: Type Playground.playground:12:18: error: 'init' is a member of the >type; 错误:键入Playground.playground:12:18:错误:“ init”是> type的成员; use 'type(of: ...)' to initialize a new object of the same dynamic >type var typeClone2 = type( of: tMirror.children.first!.value ).init() ^ type(of: ) 使用'type(of:...)'初始化具有相同动态的新对象> type var typeClone2 = type(of:tMirror.children.first!.value).init()^ type(of:)

What do I have to do to make this work? 我必须做些什么才能使这项工作? Thanks in advance! 提前致谢!

Your code won't work but the error you get is wrong so you should ignore it. 您的代码将不起作用,但是您得到的错误是错误的,因此您应该忽略它。

The real problem is you can't just blindly call init() on the type of an Any . 真正的问题是您不能只对Any类型盲目地调用init() There are a lot of types that don't have an init() at all. 许多类型根本没有init() It works on type(of: s) in your first example because the compiler knows at compile-time that the type is String (and that String has an init() ). 在第一个示例中,它适用于type(of: s) ,因为编译器在编译时就知道类型为String (并且String具有init() )。 But if you wrap it in Any then it fails as well: 但是,如果将其包装在Any则它也会失败:

let s = String("Foo") as Any
let typeClone = type(of: s).init()

Unfortunately this means there's no way to do what you're trying to do. 不幸的是,这意味着您无法做您想做的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM