Swift 复制传递的类实例 [英] Swift making copies of passed class instances
问题描述
我有一个 init 接受一个类的实例(我希望每个人都知道这意味着它是通过引用传递的)
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.
比如:
convenience init(_ item:Item?){
self.init()
self.item = item
self.undoItem = item
}
func reset(){
self.item = self.undoItem
self.reloadInfo()
}
我在应该相对简单的解决方案方面没有取得太大成功.我对 Swift 和 iOS 开发太陌生了.
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:
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))
这是一个很好且简单的函数,因此我可以快速获取我的类实例的副本.在 swift 中,由于它们是引用类型(我不确定您是否可以取消引用它或诸如此类),您基本上每次都必须为您的对象编写自定义复制函数.好吧,现在我写了这个,所以只要你使用 NSObject 的子类并使用这个协议,你就没事了.
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
这篇关于Swift 复制传递的类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!