Skip to content

Instantly share code, notes, and snippets.

@pgpt10 pgpt10/DeepShallow4.swift
Last active Jun 10, 2018

Embed
What would you like to do?
class Person: NSObject, NSCopying
{
var name: String?
var address: Address?
init(_ name: String?, _ address: Address?)
{
self.name = name
self.address = address
}
func copy(with zone: NSZone? = nil) -> Any
{
let person = Person.init(self.name, self.address)
return person
}
}
var a1 = Address("Mumbai")
var p1 = Person("John", a1)
var p2 = p1.copy() as! Person //This will create a Deep Copy of p1
print("Name: \(p1.name), City: \(p1.address?.city)") //Name: John, City: Mumbai
print("Name: \(p2.name), City: \(p2.address?.city)") //Name: John, City: Mumbai
p2.name = "Stefen"
p2.address?.city = "Bangalore"
print("Name: \(p1.name), City: \(p1.address?.city)") //Name: John, City: Bangalore
print("Name: \(p2.name), City: \(p2.address?.city)") //Name: Stefan, City: Bangalore
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.