【发布时间】:2017-10-03 18:36:27
【问题描述】:
我试图理解为什么我无法在 Swift 中使用镜像创建类的实例。在操场上,一切似乎都很好,直到下面的最后一行代码。
所以,这是第一个使用 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)
一切都按预期进行。现在,当我尝试对在镜子中找到的孩子做同样的事情时,操场会抱怨:
// 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;使用 'type(of: ...)' 来初始化相同动态 >type 的新对象 var typeClone2 = type( of: tMirror.children.first!.value ).init() ^ 类型(属于:)
我必须做些什么才能完成这项工作?提前致谢!
【问题讨论】:
标签: swift dynamic reflection types mirror