在swift子类copy()中可以这样做吗?

时间:2014-11-28 00:27:36

标签: swift copy

class SubClassType:SuperClassType {    

    override func copy() -> SubClassType {
        return super.copy() as SubClassType
    }
}

请注意,实现了超级副本,并且SubClassType不会向超类类型添加任何属性,只会修改它的功能。真的问,因为当我为行为树添加对NSCopying的支持时,我就这样输入了它,并且惊讶于抱怨者(编译器)没有对我生气。在这一点上,我在心理上对树结构如此深入,还没有准备好进行测试,但有点想知道它是否可行。我是否在思考这个问题?

3 个答案:

答案 0 :(得分:0)

您的方法

override func copy() -> AnyObject {
    let clone = super.copy() as SubClassType
    return clone
}

我的回答

我不确定你想要这个方法做什么。

let clone = super.copy() as SubClassType

将常量clone静态类型为SubClassType类型。它不会对对象进行任何更改。下一行代码

return clone

将返回值静态键入AnyObject。同样,它不会对对象进行任何更改。

代码与

相同
override func copy() -> AnyObject {
    return super.copy()
}

当您不覆盖方法时,这是默认行为。

最后,您有4行代码与0行代码相同。

答案 1 :(得分:0)

class A:NSObject {
    var something = "A's something"

    override func copy() ->AnyObject {
        let copy = A()
        copy.something = "A copy's something"
        return copy
    }
}

class SubA:A {

    override init() {
        super.init()
        self.something = "SubA something"
    }

    override func copy() ->AnyObject {

        return super.copy() as SubA // error'd: EXC Breakpoint fail!
    }

}


let a = A()
let subA = SubA()

let b = a.copy() as A
let subB = subA.copy() as SubA
好吧,我真的很懒,并且不想做深刻的复制,但最后在感谢晚餐之后更多地说我和代码。

答案 2 :(得分:0)

这也失败了。

import Cocoa


class A:NSObject {
    var something = "A's something"

    override func copy() ->AnyObject {
        let copy = A()
        copy.something = "A copy's something"
        return copy
    }
}

class SubA:A {

    override init() {
        super.init()
        self.something = "SubA something"
    }

    override func copy() ->SubA {

        return super.copy() as SubA
    }

}


let a = A()
let subA = SubA()

let b = a.copy() as A
let subB = subA.copy() as SubA