Created
June 19, 2019 12:57
-
-
Save nuclearace/453b15c9a5191cf70ed23e17c8ace641 to your computer and use it in GitHub Desktop.
Deep Copy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| protocol DeepCopyable { | |
| init(deeplyCopying: Self) | |
| } | |
| extension Array: DeepCopyable where Element: DeepCopyable { | |
| init(deeplyCopying: [Element]) { | |
| self = deeplyCopying.map(Element.init(deeplyCopying:)) | |
| } | |
| } | |
| extension Dictionary: DeepCopyable where Value: DeepCopyable { | |
| init(deeplyCopying: [Key: Value]) { | |
| self = deeplyCopying.mapValues(Value.init(deeplyCopying:)) | |
| } | |
| } | |
| class TestClass: DeepCopyable { | |
| var x: Int | |
| init(x: Int) { | |
| self.x = x | |
| } | |
| required init(deeplyCopying: TestClass) { | |
| self.x = deeplyCopying.x | |
| } | |
| } | |
| struct TestStruct: DeepCopyable { | |
| var c: TestClass | |
| init(c: TestClass) { | |
| self.c = c | |
| } | |
| init(deeplyCopying: TestStruct) { | |
| self.c = TestClass(deeplyCopying: deeplyCopying.c) | |
| } | |
| } | |
| let a = TestClass(x: 20) | |
| let b = TestStruct(c: a) | |
| print(b.c.x) | |
| a.x = 10 | |
| print(b.c.x) | |
| let c = TestStruct(deeplyCopying: b) | |
| print(c.c.x) | |
| a.x = 30 | |
| print(c.c.x) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment