Search code examples
swiftcopybehavior-tree

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


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?


Solution

  • 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.