I was hoping to use swift Mirror to create an extension that can change the properties of a struct.
It seems however that mutating the child items of the mirror is creating new instances and mutating those instead of the members of the method.
Below is a playground that shows my problem.
Can I use Mirror to achieve the goal of setting member values of structs that implement the given protocol, or should I take a different approach (and if so what)?
import Cocoa
struct Point {
var x: Int = 0
var y: Int = 0
}
protocol Shape {
var origin: Point { get }
}
extension Shape {
//: The hope is to have a generic function that will set the value of all parameters of type 'Point' but it is not working. The fact that I do not need "mutating" for this function is another clue that it will not mutate the members of the Shape.
mutating func clearAllPoints() {
let mirror = Mirror(reflecting: self)
for child in mirror.children {
// It seems the line below creates a new point instance and it is not the same member of self.
if var point = child.value as? Point {
point.x = 0
point.y = 0
}
}
}
func printAllPoints() {
let mirror = Mirror(reflecting: self)
for child in mirror.children {
if let point = child.value as? Point {
print("\(child.label!) = (x: \(point.x), y: \(point.y)")
}
}
}
}
struct Rectangle: Shape {
var origin = Point()
var corner = Point()
init() {
origin = Point(x: 10, y: 10)
corner = Point(x: 20, y: 30)
}
}
var rect = Rectangle()
//: rect has just been initialised, and the line below correctly prints all Points as initialised.
rect.printAllPoints()
//: Hope is that the line below will clear all Points but ...
rect.clearAllPoints()
//: ... it does not. The line below prints all Points with exactly the same values.
rect.printAllPoints()