【问题标题】:Swift Unable to Override Variables in SubclassSwift 无法覆盖子类中的变量
【发布时间】:2017-06-30 14:27:22
【问题描述】:

我正在使用 Swift 开发一个 macOS 项目,并且在我创建的几个类中覆盖变量时遇到了很多麻烦。在classTwo Xcode 出现错误Cannot override with a stored property 'texture' 就行了;

override var texture: SKTexture?

这是我正在使用的一些代码。

     public class classOne: SKSpriteNode {

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

还有二等;

    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
    }

我确实计划为classTwo 定义一个特定的纹理,但现在我什至无法完成这项工作。在此先感谢,如果能帮助我解决这个问题,我将不胜感激!

【问题讨论】:

标签: swift inheritance sprite-kit


【解决方案1】:

编辑

@Knight0fDragon 是对的,更好的方法是使用super.texture

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

为了覆盖该属性,您需要对其进行初始化。换句话说,给它一个初始值。如果您不想要,这里有一个解决方法:

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
}

【讨论】:

  • 不建议这样做,可能存在SKSpriteNode中的某些内容可能通过存储的变量而不是属性访问纹理的情况,从而产生不希望的结果
  • 改用 super.texture
  • 谢谢@Lawiet,@Knight0fDragon!我会尝试实现这段代码,并让你知道它是如何进行的。
  • @Jake3231 你为什么还要这样做,这种覆盖毫无意义
【解决方案2】:

试试这个

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

    }
}

显然返回一些更有用的东西。

【讨论】:

  • 谢谢!我的计划是使用SKTexture.init(imageNamed: "someImage") 为类赋予特定的纹理。我将如何使用您提供的代码来做到这一点?
  • 您是否尝试过用上面的 init 替换 SKTexture。它应该可以工作。
【解决方案3】:

从我所有的阅读来看,我不认为覆盖是你想要的方法,你想创建一个方便的 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)
    }
}

然后要使用它,你只需要做classTwo()

(注意,这还没有测试,所以我可能有错别字,但一般概念在这里)

【讨论】:

    【解决方案4】:

    在你的子类中你需要这样做。

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

    【讨论】:

      猜你喜欢
      • 2016-03-03
      • 1970-01-01
      • 1970-01-01
      • 2017-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多