Skip to content

Instantly share code, notes, and snippets.

@mehmetfarhan
Forked from sohayb/ArrayDeepCopy.swift
Created September 20, 2017 05:50
Show Gist options
  • Save mehmetfarhan/3c7d44b1d65c3c3b6d8aeb2a8b6b3920 to your computer and use it in GitHub Desktop.
Save mehmetfarhan/3c7d44b1d65c3c3b6d8aeb2a8b6b3920 to your computer and use it in GitHub Desktop.
Array deep copy in Swift
//Protocal that copyable class should conform
protocol Copying {
init(original: Self)
}
//Concrete class extension
extension Copying {
func copy() -> Self {
return Self.init(original: self)
}
}
//Array extension for elements conforms the Copying protocol
extension Array where Element: Copying {
func clone() -> Array {
var copiedArray = Array<Element>()
for element in self {
copiedArray.append(element.copy())
}
return copiedArray
}
}
//Simple Swift class that uses the Copying protocol
final class MyClass: Copying {
let id: Int
let name: String
init(id: Int, name: String) {
self.id = id
self.name = name
}
required init(original: MyClass) {
id = original.id
name = original.name
}
}
//Array cloning
let objects = [MyClass]()
//fill objects array with elements
let clonedObjects = objects.clone()
@mehmetfarhan
Copy link
Author

Thank you:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment