• Category: Creational
  • Type: object
  • Motivation: create object base on an existing object though cloning

diagram

do {
    let paul = Sheep(name: "Paul", age: 1)
    let dolly = paul.copy() as! Sheep
    dolly.name = "Dolly"
    dolly.age = 2

    print("\(paul.name) \(paul.age)")
    print("\(dolly.name) \(dolly.age)")
}
class Sheep: NSObject, NSCopying
{
    var name: String
    var age: Int

    init(name: String, age: Int)
    {
        self.name = name
        self.age = age
    }

    func copy(with zone: NSZone? = nil) -> Any
    {
        let copy = Sheep(name: name, age: age)
        return copy
    }
}