【问题标题】:Difference between official Apple code and code provided here [duplicate]Apple 官方代码与此处提供的代码之间的区别 [重复]
【发布时间】:2017-01-10 15:43:32
【问题描述】:

我只是想问一下Apple提供的SpriteKit官方更新功能和raywenderlich提供的更新功能有什么区别。为什么我应该使用 self.lastUpdate 时间而不是普通变量?这是我的代码:

import SpriteKit
class GameScene: SKScene {
private var lastUpdateTime: TimeInterval = 0
private var dt: TimeInterval = 0
override func update(_ currentTime: TimeInterval){
    if lastUpdateTime > 0 {
        dt = currentTime - lastUpdateTime
    }
    else {
        dt = 0
    }
    lastUpdateTime = currentTime
    print("\(dt * 1000) in miliseconds since last update")
}}

这里是官方功能

import SpriteKit
class GameScene: SKScene {
private var lastUpdateTime : TimeInterval = 0
override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered

    // Initialize _lastUpdateTime if it has not already been
    if (self.lastUpdateTime == 0) {
        self.lastUpdateTime = currentTime
    }

    // Calculate time since last update
    let dt = currentTime - self.lastUpdateTime

    // Update entities
    for entity in self.entities {
        entity.update(deltaTime: dt)
    }

    self.lastUpdateTime = currentTime
}

}

【问题讨论】:

  • 你的意思是self.lastUpdateTimelastUpdateTime有什么区别?如果是这样,从技术上讲是没有的——只是约定/风格的问题。
  • 是的,只是 self.lastUpdateTime 的区别
  • 非常感谢您的快速答复
  • 您需要数学解释吗?或者您希望在两种解决方案之间进行性能分析?或者您实际上想知道什么?

标签: swift sprite-kit


【解决方案1】:

在你使用它的情况下,self.lastUpdateTimelastUpdateTime 没有区别。这是个人喜好问题。

您确实需要区分以下几种情况:

  • 如果一个参数遮蔽了一个属性。这最常发生在初始化程序中,例如

    class Foo 
    {
        var property: Int
        init(property: Int)
        {
            self.property = property
        }
    }
    
  • Self 在闭包中是强制性的,作为提醒您可能的强引用循环的提示。

    class Foo
    {
        var property: Int = 1
        func bar()
        {
            DispatchQueue.main.async
            {
                print("\(self.property)") // self required here
            }
        }
    }
    

除此之外,你可以使用self 或不要使用self。在 Swift 演化的早期,有人提议将self 强制用于属性访问。这场斗争是漫长而痛苦的,但最终非强制性一方赢得了争论,所以把自己打倒吧。

【讨论】:

    猜你喜欢
    • 2011-01-07
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    • 2020-04-09
    • 2011-06-13
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    相关资源
    最近更新 更多