Mirror

struct Mirror

A representation of the substructure and display style of an instance of any type.

A mirror describes the parts that make up a particular instance, such as the instance's stored properties, collection or tuple elements, or its active enumeration case. Mirrors also provide a "display style" property that suggests how this mirror might be rendered.

Playgrounds and the debugger use the Mirror type to display representations of values of any type. For example, when you pass an instance to the dump(_:_:_:_:) function, a mirror is used to render that instance's runtime contents.

struct Point {
    let x: Int, y: Int
}

let p = Point(x: 21, y: 30)
print(String(reflecting: p))
// Prints "▿ Point
//           **x:** 21
//           **y:** 30"

To customize the mirror representation of a custom type, add conformance to the CustomReflectable protocol.

Inheritance CustomReflectable, CustomStringConvertible View Protocol Hierarchy →
Associated Types
Child = (label: String?, value: Any)

An element of the reflected instance's structure.

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.

Children = AnyCollection<Mirror.Child>

The type used to represent substructure.

When working with a mirror that reflects a bidirectional or random access collection, you may find it useful to "upgrade" instances of this type to AnyBidirectionalCollection or AnyRandomAccessCollection. For example, to display the last twenty children of a mirror if they can be accessed efficiently, you write the following code:

if let b = AnyBidirectionalCollection(someMirror.children) {
    for element in b.suffix(20) {
        print(element)
    }
}
Nested Types Mirror.AncestorRepresentation, Mirror.DisplayStyle
Import import Swift

Initializers

init<Subject>(_: Subject, children: DictionaryLiteral<String, Any>, displayStyle: Mirror.DisplayStyle?, ancestorRepresentation: Mirror.AncestorRepresentation)

Creates a mirror representing the given subject using a dictionary literal for the structure.

You use this initializer from within your type's customMirror implementation to create a customized mirror. Pass a dictionary literal with string keys as children. Although an actual dictionary is arbitrarily-ordered, when you create a mirror with a dictionary literal, the ordering of the mirror's children will exactly match that of the literal you pass.

If subject is a class instance, ancestorRepresentation determines whether ancestor classes will be represented and whether their customMirror implementations will be used. By default, the customMirror implementation of any ancestors is ignored. To prevent bypassing customized ancestors, pass .customized({ super.customMirror }) as the ancestorRepresentation parameter when implementing your type's customMirror property.

Parameters: subject: The instance to represent in the new mirror. children: A dictionary literal to use as the structure for the mirror. The children collection of the resulting mirror may be upgraded to a random access collection later. See the children property for details. displayStyle: The preferred display style for the mirror when presented in the debugger or in a playground. The default is nil. ancestorRepresentation: The means of generating the subject's ancestor representation. ancestorRepresentation is ignored if subject is not a class instance. The default is .generated.

Declaration

init<Subject>(_ subject: Subject, children: DictionaryLiteral<String, Any>, displayStyle: Mirror.DisplayStyle? = default, ancestorRepresentation: Mirror.AncestorRepresentation = default)
init<Subject, C>(_: Subject, children: C, displayStyle: Mirror.DisplayStyle?, ancestorRepresentation: Mirror.AncestorRepresentation)

Creates a mirror representing the given subject with a specified structure.

You use this initializer from within your type's customMirror implementation to create a customized mirror.

If subject is a class instance, ancestorRepresentation determines whether ancestor classes will be represented and whether their customMirror implementations will be used. By default, the customMirror implementation of any ancestors is ignored. To prevent bypassing customized ancestors, pass .customized({ super.customMirror }) as the ancestorRepresentation parameter when implementing your type's customMirror property.

Parameters: subject: The instance to represent in the new mirror. children: The structure to use for the mirror. The collection traversal modeled by children is captured so that the resulting mirror's children may be upgraded to a bidirectional or random access collection later. See the children property for details. displayStyle: The preferred display style for the mirror when presented in the debugger or in a playground. The default is nil. ancestorRepresentation: The means of generating the subject's ancestor representation. ancestorRepresentation is ignored if subject is not a class instance. The default is .generated.

Declaration

init<Subject, C>(_ subject: Subject, children: C, displayStyle: Mirror.DisplayStyle? = default, ancestorRepresentation: Mirror.AncestorRepresentation = default)
init(_:unlabeledChildren:displayStyle:ancestorRepresentation:)

Creates a mirror representing the given subject with unlabeled children.

You use this initializer from within your type's customMirror implementation to create a customized mirror, particularly for custom types that are collections. The labels of the resulting mirror's children collection are all nil.

If subject is a class instance, ancestorRepresentation determines whether ancestor classes will be represented and whether their customMirror implementations will be used. By default, the customMirror implementation of any ancestors is ignored. To prevent bypassing customized ancestors, pass .customized({ super.customMirror }) as the ancestorRepresentation parameter when implementing your type's customMirror property.

Parameters: subject: The instance to represent in the new mirror. unlabeledChildren: The children to use for the mirror. The collection traversal modeled by unlabeledChildren is captured so that the resulting mirror's children may be upgraded to a bidirectional or random access collection later. See the children property for details. displayStyle: The preferred display style for the mirror when presented in the debugger or in a playground. The default is nil. ancestorRepresentation: The means of generating the subject's ancestor representation. ancestorRepresentation is ignored if subject is not a class instance. The default is .generated.

Declaration

init<Subject, C>(_ subject: Subject, unlabeledChildren: C, displayStyle: Mirror.DisplayStyle? = default, ancestorRepresentation: Mirror.AncestorRepresentation = default)
init(reflecting:)

Creates a mirror that reflects on the given instance.

If the dynamic type of subject conforms to CustomReflectable, the resulting mirror is determined by its customMirror property. Otherwise, the result is generated by the language.

If the dynamic type of subject has value semantics, subsequent mutations of subject will not observable in Mirror. In general, though, the observability of mutations is unspecified.

subject: The instance for which to create a mirror.

Declaration

init(reflecting subject: Any)

Instance Variables

var children: Mirror.Children

A collection of Child elements describing the structure of the reflected subject.

Declaration

var children: Mirror.Children { get }
var customMirror: Mirror

The custom mirror for this instance.

If this type has value semantics, the mirror should be unaffected by subsequent mutations of the instance.

Declaration

var customMirror: Mirror { get }
var description: String

A textual representation of this instance.

Calling this property directly is discouraged. Instead, convert an instance of any type to a string by using the String(describing:) initializer. This initializer works with any type, and uses the custom description property for types that conform to CustomStringConvertible:

struct Point: CustomStringConvertible {
    let x: Int, y: Int

    var description: String {
        return "(\(x), \(y))"
    }
}

let p = Point(x: 21, y: 30)
let s = String(describing: p)
print(s)
// Prints "(21, 30)"

The conversion of p to a string in the assignment to s uses the Point type's description property.

Declaration

var description: String { get }
var displayStyle: Mirror.DisplayStyle?

A suggested display style for the reflected subject.

Declaration

var displayStyle: Mirror.DisplayStyle? { get }
var subjectType: Any.Type

The static type of the subject being reflected.

This type may differ from the subject's dynamic type when this mirror is the superclassMirror of another mirror.

Declaration

var subjectType: Any.Type { get }
var superclassMirror: Mirror?

A mirror of the subject's superclass, if one exists.

Declaration

var superclassMirror: Mirror? { get }

Instance Methods

func descendant(_:_:)

Returns a specific descendant of the reflected subject, or nil if no such descendant exists.

Pass a variadic list of string and integer arguments. Each string argument selects the first child with a matching label. Each integer argument selects the child at that offset. For example, passing 1, "two", 3 as arguments to myMirror.descendant(_:_:) is equivalent to:

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
        }
    }
}

This function is suitable for exploring the structure of a mirror in a REPL or playground, but is not intended to be efficient. The efficiency of finding each element in the argument list depends on the argument type and the capabilities of the each level of the mirror's children collections. Each string argument requires a linear search, and unless the underlying collection supports random-access traversal, each integer argument also requires a linear operation.

Parameters: first: The first mirror path component to access. rest: Any remaining mirror path components. Returns: The descendant of this mirror specified by the given mirror path components if such a descendant exists; otherwise, nil.

Declaration

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