swift - NSCopying class
swift - NSCopying class
在 Swift 2.1 中,我应该如何创建一个 class 符合 NSCopying 协议?
我试过这个:
class TargetValue: NSObject, NSCopying {
var value: Int?
func copyWithZone(zone: NSZone) -> AnyObject {
let copy = TargetValue()
copy.value = value
return copy
}
}
var target = TargetValue()
target.value = 12
var target1 = target.copy()
print(target1.value ) // ambiguous user of 'value'
但是我遇到了ambiguous user of value
的错误。我应该怎么做才能解决这个问题?
此致
copyWithZone:
returnsAnyObject
,因此您必须将副本转换为预期类型:
var target1 = target.copy() as! TargetValue
在 Swift 2.1 中,我应该如何创建一个 class 符合 NSCopying 协议?
我试过这个:
class TargetValue: NSObject, NSCopying {
var value: Int?
func copyWithZone(zone: NSZone) -> AnyObject {
let copy = TargetValue()
copy.value = value
return copy
}
}
var target = TargetValue()
target.value = 12
var target1 = target.copy()
print(target1.value ) // ambiguous user of 'value'
但是我遇到了ambiguous user of value
的错误。我应该怎么做才能解决这个问题?
此致
copyWithZone:
returnsAnyObject
,因此您必须将副本转换为预期类型:
var target1 = target.copy() as! TargetValue