Mirror.Child 标签什么时候为零?

When is Mirror.Child label nil?

Mirror.Child 个州的文档,

When the label component in not nil, it may represent the name of a stored property or an active enum case. If you pass strings to the descendant(::) method, labels are used for lookup.

什么时候 Mirror.Child label 值为零?

Mirror.Child 可以表示未标记的值,因此 labelOptional.

如果您创建一个 Mirror 来反映具有命名属性的类型(例如 structclass),label 将有一个 non-nil每个 属性 的值。但是,您也可以 Mirror 未命名的 children 事物,例如 Array.

当您 Mirror 一个 Array 时,Array 的元素将可以作为 Mirror.Child 访问,但它们的 label 将是 nil.

func mirrorChildren<T>(of object: T) {
    for child in Mirror(reflecting: object).children {
        print("Label: \(child.label ?? "nil"), value: \(child.value)")
    }
}

mirrorChildren(of: [1,2,3])

输出:

Label: nil, value: 1
Label: nil, value: 2
Label: nil, value: 3