Class copy constructors in Swift 4 for defensive copying

Swift tutorials by Notice that Swift almost seems to frown on making a copy of a reference type, i.e., a copy of an instance of a class, or, as some would rather put it, getting a copy of an object. I’m not talking about getting another reference to a class, I’m talking about getting an entire, separate copy of a class instance. This frowning on class copying is not an accident. Swift’s language architects want the syntax and semantics of the language to be crystal clear. They want developers to be confident that reference types and value types will both have 1) distinct and obvious meanings and that both types will 2) behave consistently. But still, why not be able to safely make a copy of a class instance? I’ll show you how in this tutorial by borrowing the copy constructor concept from C++. In Swift, we’d call this a “copy initializer.” (NOTE: Yeah, yeah, yeah, I know about NSCopying in Cocoa and Objective-C.)

Continue reading “Class copy constructors in Swift 4 for defensive copying”