How to copy Objects in Swift

I wanted to populate an array with multiple unique copies of an existing object. If you just append the same object in a loop, you just end up with an array with multiple references to the one object!

I thought that there would be a simple way to copy the instance of an object in Swift. I was wrong! The simplest way is to use copy() which requires the following three steps:

  1. Make your class conform to NSCopying. This isn’t strictly required, but it makes your intent clear.
  2. Implement the method copy(with:), where the actual copying happens.
  3. Call copy() on your object.

See hackingwithswift.com for more details…

 

Leave a Reply

Your email address will not be published. Required fields are marked *