swiftambiguousnscopying

swift - NSCopying class


In Swift 2.1, how should I create a class conforming NSCopying protocol?

I tried this:

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'

But I hit the error of ambiguous user of value. What should I do to fix this problem?

Regards


Solution

  • copyWithZone: returns AnyObject, so you have to cast the copy to the expected type:

    var target1 = target.copy() as! TargetValue