2016-03-23 16 views
0

在Swift 2.1中,我应该如何创建一个符合NSCopying协议的类?swift - 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错误。我该怎么办才能解决这个问题?

问候

回答

2

copyWithZone:回报AnyObject,所以你必须拷贝转换为预期的类型:

var target1 = target.copy() as! TargetValue 
+0

愚蠢的我错过这个!非常感谢,特洛伊 – quanguyen