From the course: Practical Design Patterns in Swift

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Cloning reference types

Cloning reference types - Swift Tutorial

From the course: Practical Design Patterns in Swift

Start my 1-month free trial

Cloning reference types

- [Instructor] Reference types don't get the copy behavior for free. To implement the prototype pattern, reference types need to adopt the NSCopying protocol. The NSCopying protocol declares the copyWithZone method which lets us create clones of a given object. Let's add NSCopying conformance to the nameClass type. You can open the project from the exercise files folder chapter 334, begin. So, I make our nameClass class conform to the NSCopying protocol. It's undeclared because we need to import the foundation framework, let's do it now. Next, we need to implement the copyWithZone method. The method simply returns a new instance and passes the property values of the object to the newly created one. So, let's return, the nameClass, with the first name set to self, first name and last name set to self last name. It is not possible to overload the default assignment operator, thus, we must explicitly call the Copy method during assignment. So, I'm going to change this line, to…

Contents