Introduction: This is a request for a copy constructor mechanism for structs in Swift.
Motivation: Suppose you have a class stored inside a struct, like so: class C { func copy() -> C { … } } struct S { var i: Int var c: C } and you create a couple of the structs, like so: let c = C() let foo = S(i: 1, c: c) var bar = foo bar.i = 2 Since the ‘bar’ variable was mutated, it now contains a copy of the original ‘foo’ struct. However, both structs still carry the same pointer to ‘c'. There may be cases where you would want a copy of the struct to make a copy of any reference types stored within; however, that does not seem to be possible currently. Proposed Solution: Adding a copy constructor to S that would be called when a copy of the struct is about to be made. This constructor would simply create a new instance, initialize it, and return it. The copy constructor would look like this: struct S { var i: Int var c: C copy { return S(i: self.i, c: self.c.copy()) } } Structs that do not implement the copy constructor would get the same behavior as they do currently. Impact on Existing Code: There should be no impact on existing code that does not implement the copy constructor. Charles _______________________________________________ swift-evolution mailing list swift-evolution@swift.org https://lists.swift.org/mailman/listinfo/swift-evolution