Mirror

struct Mirror

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

Inheritance CustomReflectable, CustomStringConvertible
Associated Types
public typealias Child = (label: String?, value: Any)

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.

public typealias Children = AnyCollection<Mirror.Child>

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

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.

Initializers

init init(_:children:displayStyle:ancestorRepresentation:) Required

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.

Declaration

public init<Subject, C>(_ subject: Subject, children: C, displayStyle: Mirror.DisplayStyle? = nil, ancestorRepresentation: Mirror.AncestorRepresentation = .generated) where C: Collection, C.Element == Mirror.Child
init init(_:children:displayStyle:ancestorRepresentation:) Required

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.

Declaration

public init<Subject>(_ subject: Subject, children: KeyValuePairs<String, Any>, displayStyle: Mirror.DisplayStyle? = nil, ancestorRepresentation: Mirror.AncestorRepresentation = .generated)
init init(_:unlabeledChildren:displayStyle:ancestorRepresentation:) Required

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.

Declaration

public init<Subject, C>(_ subject: Subject, unlabeledChildren: C, displayStyle: Mirror.DisplayStyle? = nil, ancestorRepresentation: Mirror.AncestorRepresentation = .generated) where C: Collection
init init(reflecting:) Required

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.

  • Parameter subject: The instance for which to create a mirror.

Declaration

public init(reflecting subject: Any)

Instance Variables

let children Required

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

Declaration

let children: Mirror.Children
var customMirror Required

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
var description Required

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
let displayStyle Required

A suggested display style for the reflected subject.

Declaration

let displayStyle: Mirror.DisplayStyle?
let subjectType Required

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

let subjectType: Any.Type
var superclassMirror Required

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

Declaration

var superclassMirror: Mirror?

Instance Methods

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

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.

Declaration

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