“This is the 12th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

  • We saw that beforeMirrorThe method of use, as well as throughMirror parsing JsonConvert to Model. This article is mainly introducedMirrorThe principle of

1. Source code analysis

  • inMirror.swiftFound in the fileMirrorIs a struct type

The initialization method determines whether the passed object subject complies with the CustomReflectable protocol. If so, the attributes of the object are determined through the customMirror. Otherwise, use internalReflecting to initialize.

  • internalReflectingTo view

Mainly: 1. Pass_getNormalizedTypeMethod to get thesubject2. Get the number of attributes of the object, and iterate over the attributes stored in the dictionary. 3. Set to get the parent classMirror, so the Mirror has asuperclassMirrorProperty, returns the parent class of the class. 4. Set theMiroorthedisplayStyleProperties. 5. SetsubjectType _defaultDescendantRepresentationProperties.

  • To view_getNormalizedTypeThe implementation of the

A compile field is used above the function@_silgen_nameThis is one from SwiftHidden symbols, the function is to connect aC/C++The function is mapped directly to thetaSwift function. So we’re calling_getNormalizedTypeFunction, will eventually call C++swift_reflectionMirror_normalizedType -> Callmethods

We look at thecallThe implementation of the

There are mainly class calls and non-class calls, and non-class IMPL implementations are judged by an enumerationReflectionMirrorImplIt throughkindTo determine the type of the instance and get the corresponding of the different typesimpl, call non-classcall(&impl). Classes are callscallClass.

The types of ReflectionMirrorImpl are as follows:

  • Reflection of the TupleImpl tuple
  • Reflection of StructImpl structure
  • EnumImpl Enumeration reflection
  • Reflection of the ClassImpl class
  • Reflection of MetatypeImpl metadata
  • OpaqueImpl Opaque type of reflection

Let’s look at StructImpl as an example

throughisReflectableFunction to determine whether or not to accept reflection, its implementation is nothing more than to getDescriptionThrough theDescriptionisReflectableDelta function. In obtainingcountIt’s time to use itisReflectableFunction, code as follows:

If reflection is not supported, return 0 directly, otherwise go below and call onegetInfoFunction. To viewgetInfoFunction, which is implemented as follows:

We see thegetFieldAtThe implementation of the

To get hereDescriptionThrough theDescriptiongetFieldsAnd theFieldsIt contains the property information, now that you’ve got itFieldsTo get information about attributes.

2. Summary

The Mirror creates a structure inside the meatadata of the instance object, which is used to output metadata descriptor, find name and numFields in Descriptor, and fields in FieldDescriptor, To find a description of the current property, and then move the pointer to get the other properties