当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Swift Mirror descendant(_:_:)用法及代码示例


实例方法

descendant(_:_:)

返回反射主题的特定后代,如果不存在这样的后代,则返回 nil

声明

func descendant(
    _ first: MirrorPath,
    _ rest: MirrorPath...
) -> Any?

返回值

如果存在这样的后代,则由给定的镜像路径组件指定此镜像的后代;否则,nil

参数

first

要访问的第一个镜像路径组件。

rest

任何剩余的镜像路径组件。

详述

传递字符串和整数参数的可变参数列表。每个字符串参数选择具有匹配标签的第一个孩子。每个整数参数都选择该偏移处的孩子。例如,将 1, "two", 3 作为参数传递给 myMirror.descendant(_:_:) 等效于:


var result: Any? = nil
let children = myMirror.children
if let i0 = children.index(
    children.startIndex, offsetBy: 1, limitedBy: children.endIndex),
    i0 != children.endIndex
{
    let grandChildren = Mirror(reflecting: children[i0].value).children
    if let i1 = grandChildren.firstIndex(where: { $0.label == "two" }) {
        let greatGrandChildren =
            Mirror(reflecting: grandChildren[i1].value).children
        if let i2 = greatGrandChildren.index(
            greatGrandChildren.startIndex,
            offsetBy: 3,
            limitedBy: greatGrandChildren.endIndex),
            i2 != greatGrandChildren.endIndex
        {
            // Success!
            result = greatGrandChildren[i2].value
        }
    }
}

此函数适用于探索 REPL 或游乐场中的镜像结构,但并非旨在提高效率。在参数列表中查找每个元素的效率取决于参数类型和镜像children 集合的每个级别的函数。每个字符串参数都需要线性搜索,除非底层集合支持随机访问遍历,否则每个整数参数也需要线性操作。

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

相关用法


注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 Mirror descendant(_:_:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。