Skip to content

Instantly share code, notes, and snippets.

@sohayb
Last active October 13, 2023 07:58
Show Gist options
  • Star 33 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save sohayb/4ba350f7e45c636cb3c9 to your computer and use it in GitHub Desktop.
Save sohayb/4ba350f7e45c636cb3c9 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()
@ankushkushwaha
Copy link

Nice gist.

@lmorit
Copy link

lmorit commented Jul 18, 2018

indeed!

@Hazoomo
Copy link

Hazoomo commented Sep 2, 2018

Thanks thats great!

@dipkasyap
Copy link

Thanks for sharing.

@seyoung-hyun
Copy link

Thanks for your code!

Can you let me know which license is used for distribution of this code?
I'd like to use this code for a commercial app so I need to check the license.

Happy coding! :)

@FedeCugliandolo
Copy link

thanks for sharing this!

@javadba
Copy link

javadba commented May 14, 2020

Is append() going to be slow since it is invoked once per element in the source array?

@sohayb
Copy link
Author

sohayb commented May 22, 2020

@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.

@sohayb
Copy link
Author

sohayb commented May 22, 2020

@seyoung-hyun pretty sorry for the very late reply 😅 it's MIT License.

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