如何从 Swift 中的镜像 object 的 child 创建 class 的实例

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

我想了解为什么我无法使用 Swift 中的镜像创建 class 的实例。在操场上,一切似乎都很好,直到下面的最后一行代码。

所以,这是第一个使用 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)

一切正常。现在,当我尝试用在镜子 object 中发现的 child 做同样的事情时,游乐场抱怨:

// 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()

带有"typeClone2"的那一行是失败的。如果我分解表达式并检查事物,似乎所有类型和值都是相似的,如第一个示例。但在第二种情况下,游乐场会发出此错误:

游乐场执行失败:

error: Type Playground.playground:12:18: error: 'init' is a member of the >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: )

我需要做什么才能完成这项工作?提前致谢!

您的代码无法运行,但您得到的错误是错误的,因此您应该忽略它。

真正的问题是你不能盲目地调用 init() 类型的 Any。有很多类型根本没有 init()。它在您的第一个示例中适用于 type(of: s),因为编译器在编译时知道类型是 String(并且 String 有一个 init())。但是如果你把它包装在 Any 那么它也会失败:

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

不幸的是,这意味着无法执行您想要执行的操作。