You either have to, as @MarioZannone mentioned, make it a structure, because the structures are automatically copied, or you may not need a structure and need a class. To do this, you need to determine how to copy your class. There is an NSCopying protocol that combines this in the ObjC world, but it makes your Swift code βunacceptableβ in that you must inherit from NSObject . However, I suggest defining your own copy protocol as follows:
protocol Copying { init(original: Self) } extension Copying { func copy() -> Self { return Self.init(original: self) } }
which you can implement as follows:
class Test : Copying { var x : Int init() { x = 0 }
Inside the initializer, you need to copy the entire state from the passed original Test to self . Now that you have executed the protocol correctly, you can do something like this:
let original = Test() let stillOriginal = original let copyOriginal = original.copy() original.x = 10 original.x
This is basically the same as NSCopying without ObjC
EDIT: Unfortunately, this beautiful protocol works very poorly with a subclass ...
source share