Is this ok to do in a swift subclass copy()?

713 views Asked by At
class SubClassType:SuperClassType {    

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

Note that the super copy is implemented and the SubClassType doesn't add any properties to the super class type, only modifies it's functionality. Really asking because as I was adding support for NSCopying for a behavior tree I typed it in like that and was amazed that the complainer (compiler) didn't get mad at me. I'm so deep in tree structures mentally at this point and not ready to test yet, but kinda wanted to see if it could work or not. Am I overthinking the issue?

3

There are 3 answers

2
Jeffery Thomas On BEST ANSWER

Your Method

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

My Answer

I'm not sure exactly what you want the method to do.

let clone = super.copy() as SubClassType

statically types the constant clone to be of type SubClassType. It doesn't make any changes to the object. The very next line of code

return clone

statically types the return value to be AnyObject. Again, it doesn't make any changes to the object.

The code is identical to

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

Which is the default behavior when you don't override a method.

In the end, you have 4 lines of code that are identical to 0 lines of code.

0
FrostyL On
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

ok really I was being lazy and didn't want to have to do a deep copy but in the end that say's more about me and code after Thanks Giving dinner.

0
FrostyL On

This fails too.

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