0

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

quanguyen
  • 1,443
  • 3
  • 17
  • 29

1 Answers1

2

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

var target1 = target.copy() as! TargetValue
tktsubota
  • 9,371
  • 3
  • 32
  • 40