gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:07:07 25 4
gpt4 key购买 nike

我试图理解为什么我无法在 Swift 中使用镜像创建类的实例。在 Playground 上,一切看起来都很好,直到下面的最后一行代码。

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

一切都按预期进行。现在,当我尝试对镜子对象中发现的 child 做同样的事情时, Playground 会提示:

// 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”的行是失败的行。如果我分解表达式并检查事物,似乎所有类型和值都是相似的,如第一个示例所示。但在第二种情况下, Playground 会发出此错误:

Playground 执行失败:

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: )

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

最佳答案

您的代码将无法工作,但您收到的错误是错误的,因此您应该忽略它。

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

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

不幸的是,这意味着无法完成您想要做的事情。

关于swift - 如何在 Swift 中从 Mirror 对象的子对象创建类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46551253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com