Swift making copies of passed class instances

2019-07-26 17:59发布

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.

2条回答
Bombasti
2楼-- · 2019-07-26 18:04

Wrote the following (with the help of a friend) in playground:

protocol Copyable {
   func copyOfValues() -> AnyObject
}

extension Copyable where Self: NSObject {
    func copyOfValues() -> AnyObject{
        var copyOfOriginal = Self()
        let mirror = Mirror(reflecting: self)
        for (label, value) in mirror.children {
            if let label = label {
                copyOfOriginal.setValue(value, forKey: label)
            }
       }

        return copyOfOriginal
    }
}

class Test: NSObject, Copyable {
    var a = 1
    var b = 2
}

var test = Test()
var copy = test.copyOfValues() as! Test

print(dump(test))
print(dump(copy))
copy.a = 10
print(dump(test))
print(dump(copy))

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

查看更多
Animai°情兽
3楼-- · 2019-07-26 18:09

Use of swift structures could be an option for you.

struct Item {
    //
}

Structures in Swift are value types, and they are copied by value rather than reference.

Example

struct Item {
    var value: Int = 1
}

var item1 = Item()
var item2 = item1
item2.value = 20

print("\(item1.value)") // 1
print("\(item2.value)") // 20

In the above example item1.value is 1 and item2.value is 20. The following line creates a copy of item1 and assigns it to item2:

var item2 = item1

From this line any change to item2 is not reflected in item1.

Conclusion

Your problem can be solved by defining Item as a struct

查看更多
登录 后发表回答