I have an init that takes in an instance of a class (which I hope everyone knows that that means it's pass-by-reference)
I want to be able to copy the object and store in on two class instance variables, such that, I have a function that is meant to act as a "reset" where it will set any changes I had made up to a certain point go back to what it was before.
so something like:
convenience init(_ item:Item?){
self.init()
self.item = item
self.undoItem = item
}
func reset(){
self.item = self.undoItem
self.reloadInfo()
}
I haven't had much success with what should be a relatively straight forward solution. I'm just too new to Swift and iOS development.
Wrote the following (with the help of a friend) in playground:
This is a nice and simple function so that I can obtain copy of my class instances in swift. In swift, since they are a reference type (and I am not sure if you can dereference it or whatnot) you would basically have to write a custom copy function for your objects every time. Well, Now I wrote this, so as long as you are using a subclass of NSObject and use this protocol, you'll be fine.
This has worked exactly as I need in my code
Use of swift structures could be an option for you.
Structures in Swift are value types, and they are copied by value rather than reference.
Example
In the above example
item1.value
is1
anditem2.value
is20
. The following line creates a copy of item1 and assigns it to item2:From this line any change to
item2
is not reflected initem1
.Conclusion
Your problem can be solved by defining
Item
as astruct