Skip to content

Instantly share code, notes, and snippets.

@nuclearace
Created June 19, 2019 12:57
Show Gist options
  • Select an option

  • Save nuclearace/453b15c9a5191cf70ed23e17c8ace641 to your computer and use it in GitHub Desktop.

Select an option

Save nuclearace/453b15c9a5191cf70ed23e17c8ace641 to your computer and use it in GitHub Desktop.
Deep Copy
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