Swift Mirroring is one of the most powerful yet under used feature of the Swift language. The ability to dynamically extract the meta data of a class instance is used
Surprising Swift mirroring is pretty straight forward. The implementation below dynamically reads the properties associated with the Flower struct and prints them on the output window.
But we can do much more than simply printing it on the output window. We can use the Swift mirroring techniques to create a generic data access layer for simple CRUD (Create Read Update Delete) operations.
Here is a simple generic save function using the Vapor SQLite provider.
The magic happens in the prepareInsertSQL function which utilizes Swift mirroring to create the required sql.
In prepareInsertSQL we dynamically create the required SQL required to insert the entity. The usage is shown below:
Now, we have created a very basic generic “save” function which can use the powers of the Swift mirroring to dynamically generate SQL and insert the data into the SQLite database.