Last active
October 25, 2024 04:07
-
-
Save sohayb/4ba350f7e45c636cb3c9 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
@javadba from my testing and with the needs I had at the time, it didn't impact the performance of the app at all. But tbh, I didn't stress-test it.