Reputation: 299
A very simple example of iOS Swift inheritance with the copy constructor. When I try to compile this, Xcode complains that I'm overriding a function that was defined with the parameter type Base and in child it's Child.
I agree with the compiler that the type is different but still he should let me do it somehow without using a different function name...
import Foundation
import SpriteKit
class Base : SKSpriteNode
{
private var a : Int = 0
init(other: Base)
{
self.a = other.a
super.init(fileNamed: "test")
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
}
class Child : Base
{
private var b : Int = 0
init(other: Child)
{
self.b = other.b
super.init(other: other)
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
}
So is there a way of doing this in Xcode 6 and Swift please? Cheers, TK
Edit: Unfortunately I wrote my question so that it's easily misunderstood. So it's really only about the copy constructor and nothing else. Adjusted the code from a simple pseudo code to actual code that does not compile because of the mentioned problem.
Upvotes: 1
Views: 2761
Reputation: 71
Being a base class, Base does not need to call a designated initialiser from a superclass, since it does not have one. Remove that and all should be well.
Also, I believe your call to super in the child-class initialiser should come after assignment of local iVars.
class Base
{
private var a : Int = 0
init(other: Base)
{
self.a = other.a
}
}
class Child : Base
{
private var b : Int = 0
init(other: Child)
{
self.b = other.b
super.init(other: other)
}
}
Edit due to re-phrase of question:
Your 'Base' class must now call a designated initialiser from the super-class. In this case, init(texture: SKTexture!, color: UIColor!, size: CGSize)
.
In your 'Child' class, you could check to see if other is of type Child and if so cast appropriately.
override init(other: Base)
{
if other is Child {
self.b = (other as! Child).b
}
super.init(other: other)
}
Also see top answer in How to implement copy constructor in Swift subclass? for further help.
Upvotes: 3