我怎样才能不断检查bool的值是真是假? SWIFT

时间:2017-03-18 06:12:58

标签: swift sprite-kit boolean

您好我的问题很简单我必须不断检查bool的值是真还是假,到目前为止我尝试过的是使用:

override func update(_ currentTime: TimeInterval) 

在swift中运行,它是快速的方式,一旦它检查值,它将不断重复动作,即使我只希望它只执行一次动作,所以基本上我所说的是所有我想做的是检查bool值是真还是假一次,然后停止检查,直到它再次发生变化。请帮忙,谢谢。

2 个答案:

答案 0 :(得分:5)

财产观察员

你可以在Swift中使用Property Observers来完成你需要的东西......以下是docs对这些内容的说法:

  

财产观察员观察并回应房产的变化   值。每次物业的价值都会调用物业观察员   设置,即使新值与属性的当前值相同   值。

willSetdidSet属性观察员:

  • 将在存储值之前调用willSet。

  • 在存储新值后立即调用didSet。

要解决您的问题,您可以执行以下操作:

 var myProperty:Int = 0 {

        willSet {
           print("About to set myProperty, newValue = \(newValue)")
        }

        didSet{
            print("myProperty is now \(myProperty). Previous value was \(oldValue)")
        }
    }

您可以在您的媒体资源上实施一个或两个属性观察者。

Getters and Setters

作为替代方案,您可以在存储的属性上使用getter和setter来解决您的问题:

private var priv_property:Int = 0

var myProperty:Int{

    get {
        return priv_property
    }

    set {
        priv_property = newValue
    }
}

计算属性实际上不存储值。相反,它们提供了一个getter和一个可选的setter来间接检索和设置其他属性和值。

答案 1 :(得分:0)

您应该使用观察者或回调。阅读下面的评论并查看@ Whirlwind的答案。以下解决方案并不是真正推荐的,因为它效率低下并且可能使代码复杂化。但如果您想要或需要在update()中执行此操作,请按以下步骤操作:

// Assume stored property
// It might be an API call and so on
var boolToWatch = false

var lastValueOfWatchedBool: Bool?
var lastCheck: TimeInterval = 0
let checkInterval = 1.0 // check every second

override func update(_ currentTime: TimeInterval) {

    // In case boolToWatch is an expensive API call might be good to
    // check less frequently
    if currentTime - lastCheck > checkInterval {
        lastCheck = currentTime

        // Check for the initial case
        if lastValueOfWatchedBool == nil {
            lastValueOfWatchedBool = boolToWatch
        }

        // Detect change
        if boolToWatch != lastValueOfWatchedBool {
            lastValueOfWatchedBool = boolToWatch

            // Do what you need to do when the value changed here
            print("I feel different!")
        }
    }
}