-
-
Save CocoaDebug/37142b61102286c77d7f5d4ee6f450dd to your computer and use it in GitHub Desktop.
Array deep copy 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
//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