我希望能够在 Swift 中复制自定义类。到目前为止,一切都很好。在 Objective-C 中,我只需要实现 NSCopying
协议(protocol),这意味着实现 copyWithZone
。
例如,我有一个名为 Value
的基本类,它存储一个 NSDecimalNumber
。
func copyWithZone(zone: NSZone) -> AnyObject! {
return Value(value: value.copy() as NSDecimalNumber)
}
在 Objective-C I 中,可以很容易地调用 copy
来复制我的对象。在 Swift 中,似乎没有办法调用 copy
。即使不需要区域,我真的需要调用 copyWithZone
吗?我需要将哪个区域作为参数传递?
最佳答案
copy
方法在NSObject
中定义。如果您的自定义类未继承自 NSObject
,则copy
将不可用。
您可以通过以下方式为任何对象定义copy
:
class MyRootClass {
//create a copy if the object implements NSCopying, crash otherwise
func copy() -> Any {
guard let asCopying = ((self as AnyObject) as? NSCopying) else {
fatalError("This class doesn't implement NSCopying")
}
return asCopying.copy(with: nil)
}
}
class A : MyRootClass {
}
class B : MyRootClass, NSCopying {
func copy(with zone: NSZone? = nil) -> Any {
return B()
}
}
var b = B()
var a = A()
b.copy() //will create a copy
a.copy() //will fail
我想 copy
并不是真正的复制对象的纯 Swift 方式。在 Swift 中,创建复制构造函数(采用相同类型对象的初始化程序)可能是一种更常见的方法。
关于swift - 在 Swift 中实现 copy(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24242629/