Last active
February 25, 2020 13:46
-
-
Save imthath-m/ff11bb343af877f3f9195a071ced03c3 to your computer and use it in GitHub Desktop.
Conform to this protocol to easily deep copy reference types in Swift.
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
import Foundation | |
public protocol Imitable: Codable { | |
var copy: Self? { get } | |
} | |
extension Imitable { | |
public var copy: Self? { | |
guard let data = try? JSONEncoder().encode(self) else { return nil } | |
return try? JSONDecoder().decode(Self.self, from: data) | |
} | |
} | |
final class Person: Imitable, CustomStringConvertible { | |
var name: String | |
var age: Int | |
// add any number of required properties | |
init(name: String, age: Int) { | |
self.name = name | |
self.age = age | |
} | |
var description: String { "My name is \(name) and my age is \(age)" } | |
} | |
// MARK: Example usage | |
func testImitable() { | |
var basith = Person(name: "Basith", age: 24) | |
var aslam = basith.copy! // use "guard" or "if let" to be safe | |
print(aslam) | |
print(basith) | |
aslam.name = "Aslam" | |
basith.age = 25 | |
print(aslam) // only name is changed in this object | |
print(basith) // only age is changed in this object | |
// both objects refer to different memory locations | |
} | |
testImitable() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment