“This is the 12th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”
- We saw that before
Mirror
The method of use, as well as throughMirror parsing Json
Convert to Model. This article is mainly introducedMirror
The principle of
1. Source code analysis
- in
Mirror.swift
Found in the fileMirror
Is 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.
internalReflecting
To view
Mainly: 1. Pass_getNormalizedType
Method to get thesubject
2. 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 asuperclassMirror
Property, returns the parent class of the class. 4. Set theMiroor
thedisplayStyle
Properties. 5. SetsubjectType
和 _defaultDescendantRepresentation
Properties.
- To view
_getNormalizedType
The implementation of the
A compile field is used above the function@_silgen_name
This is one from SwiftHidden symbols
, the function is to connect aC/C++
The function is mapped directly to thetaSwift function
. So we’re calling_getNormalizedType
Function, will eventually call C++swift_reflectionMirror_normalizedType -> Call
methods
We look at thecall
The implementation of the
There are mainly class calls and non-class calls, and non-class IMPL implementations are judged by an enumerationReflectionMirrorImpl
It throughkind
To 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
throughisReflectable
Function to determine whether or not to accept reflection, its implementation is nothing more than to getDescription
Through theDescription
的 isReflectable
Delta function. In obtainingcount
It’s time to use itisReflectable
Function, code as follows:
If reflection is not supported, return 0 directly, otherwise go below and call onegetInfo
Function. To viewgetInfo
Function, which is implemented as follows:
We see thegetFieldAt
The implementation of the
To get hereDescription
Through theDescription
getFields
And theFields
It contains the property information, now that you’ve got itFields
To 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