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:
- Make your class conform to
NSCopying. This isn’t strictly required, but it makes your intent clear.
- Implement the method
copy(with:), where the actual copying happens.
copy()on your object.
See hackingwithswift.com for more details…