【问题标题】:swift - NSCopying classswift - NSCopying 类
【发布时间】:2016-03-23 04:05:11
【问题描述】:

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

问候

【问题讨论】:

    标签: swift ambiguous nscopying


    【解决方案1】:

    copyWithZone: 返回AnyObject,因此您必须将副本转换为预期的类型:

    var target1 = target.copy() as! TargetValue
    

    【讨论】:

    • 愚蠢地错过了这个!非常感谢,特洛伊
    猜你喜欢
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 2010-12-30
    • 2011-05-27
    • 2011-05-04
    • 1970-01-01
    • 2015-06-30
    • 1970-01-01
    相关资源
    最近更新 更多