Jake3231
Jake3231

Reputation: 713

Swift Unable to Override Variables in Subclass

I am working on a macOS project in Swift, and I've been having a lot of trouble with overriding variables in a few classes I've made. In classTwo Xcode is presenting the error Cannot override with a stored property 'texture' on the line;

override var texture: SKTexture?

This is a bit of the code I'm using.

     public class classOne: SKSpriteNode {

        required public init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
// Other functions
    }

And the second class;

    class classTwo: classOne {
        override var texture: SKTexture? // Cannot override with a stored property 'texture'

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
// Some other functions
    }

I do plan to actually define a specific texture for classTwo, but for now I couldn't even make this work.. Thanks in advance, and I'd appreciate any help on solving this issue!

Upvotes: 3

Views: 1877

Answers (4)

Lawliet
Lawliet

Reputation: 3499

EDIT

@Knight0fDragon was right, a better approach is to use super.texture

class classTwo: classOne {
    override var texture:SKTexture? {
        get {
            return super.texture
        }
        set {
            super.texture = newValue
        }
    }            
}

In order to override the property you need to initialise it. In other words, giving it an initial value. If you don't want, here is a workaround:

class classTwo: classOne {    
    var _texture:SKTexture
    override public var texture: SKTexture? {
        get {
            return _texture
        }
        set {
            _texture = newValue!
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // Some other functions
}

Upvotes: 4

Kwaku Eshun
Kwaku Eshun

Reputation: 149

In your subclass you need to do this.

override var texture:SKTexture? {
    get { 
        return super.texture
    }
    set {
        super.texture = newValue
    }
}

Upvotes: 1

Knight0fDragon
Knight0fDragon

Reputation: 16837

From all my reading, I do not think overriding is the approach you want, you want to create a convenience init

class classTwo: classOne {
    convenience init()
    {
        let texture = SKTexture(imageNamed:"myImage")
        self.init(texture,.white,texure.size)
    }    

    required init?(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
    }
}

Then to use it, you just need to do classTwo()

(Note, this has not been tested, so I may have typos, the general concept is here though)

Upvotes: 0

iCyberPaul
iCyberPaul

Reputation: 650

Try this

override var texture: SKTexture? {
    get {
        return SKTexture()
    }
    set {

    }
}

obviously returning something a bit more useful.

Upvotes: 1

Related Questions