Skip to content

Instantly share code, notes, and snippets.

@CocoaDebug
Forked from sohayb/ArrayDeepCopy.swift
Created January 8, 2018 15:42
Show Gist options
  • Save CocoaDebug/37142b61102286c77d7f5d4ee6f450dd to your computer and use it in GitHub Desktop.
Save CocoaDebug/37142b61102286c77d7f5d4ee6f450dd 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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment