How to copy or duplicate an objects in Swift?

Shallow copy

class Student {
var name: String

init(_ name: String) {
self.name = name
}
}
let originalStudent = Student("John")
print(originalStudent) // Output: John

let shallowCopy = originalStudent
originalStudent = "Amelia"
print(originalStudent.name) // Output: Amelia
print(shallowCopy.name) // Output: Amelia

Deep Copy

1. Initialiser:

let deepCopy = Student(originalStudent.name)
originalStudent.name = "Smith"
print(originalStudent.name) // Output: Smith
print(deepCopy.name) // Output: Amelia
let originalStudent = Student("Leo")
print(originalStudent.name) // Output: Leo

let deepCopy = originalStudent.copy() as! Student
originalStudent.name = "Noah"
print(originalStudent.name) // Output: Noah
print(deepCopy.name) // Output: Leo

2. Codable:

struct Student: Codable {
var name: String
}

var originalStudent = Student(_ name: "John")

let encoder = JSONEncoder()
let decoder = JSONDecoder()

do {
let encodedData = try encoder.encode(originalStudent)
let copiedStudent = try decoder.decode(Student.self, from: encodedData)
originalStudent.name = "Smith"
print(originalStudent.name) // Output: Smith
print(copiedStudent.name) // Output: John
} catch {
print("Error: \(error)")
}

NSObject:

class Student: NSObject, NSCopying {

var name: String

init(_ name: String) {
self.name = name
}

func copy(with zone: NSZone? = nil) -> Any {
return Student(name)
}
}

Conclusion:

--

--

Evangelist Apps specializes in developing iOS apps using latest Apple tools and technlogy. We help build apps to suit the customer’s needs and to take their business to the next level.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vinodh Kumar

Senior iOS developer @EvangelistSoftware | Passionate programmer.