Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

ankushkushwaha commented Jul 13, 2018

Nice gist.

@lmorit

This comment has been minimized.

Copy link

lmorit commented Jul 18, 2018

indeed!

@Hazoomo

This comment has been minimized.

Copy link

Hazoomo commented Sep 2, 2018

Thanks thats great!

@dipkasyap

This comment has been minimized.

Copy link

dipkasyap commented Oct 30, 2018

Thanks for sharing.

@seyoung-hyun

This comment has been minimized.

Copy link

seyoung-hyun commented Nov 20, 2018

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

This comment has been minimized.

Copy link

FedeCugliandolo commented Jul 18, 2019

thanks for sharing this!

@javadba

This comment has been minimized.

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

This comment has been minimized.

Copy link
Owner 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

This comment has been minimized.

Copy link
Owner 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
You can’t perform that action at this time.