你好我的問題很簡單我必須不斷地檢查一個布爾值是否是真還是假,我迄今嘗試是使用:如何經常檢查bool的值是否爲真/假? SWIFT
override func update(_ currentTime: TimeInterval)
功能迅速,這是方式快速和一旦它檢查值將不斷重複的行動,即使我只希望它只執行一次行動,所以基本上我說的是,我想要做的就是檢查布爾值是否爲真或者一次假,然後停止檢查直到它再次改變。請幫忙,謝謝。
你好我的問題很簡單我必須不斷地檢查一個布爾值是否是真還是假,我迄今嘗試是使用:如何經常檢查bool的值是否爲真/假? SWIFT
override func update(_ currentTime: TimeInterval)
功能迅速,這是方式快速和一旦它檢查值將不斷重複的行動,即使我只希望它只執行一次行動,所以基本上我說的是,我想要做的就是檢查布爾值是否爲真或者一次假,然後停止檢查直到它再次改變。請幫忙,謝謝。
地產觀察家
您可以使用屬性觀察員斯威夫特完成你所需要的...這裏是文檔說這些是什麼:
地產觀察者觀察和在變化作出反應物業的價值 。每次屬性值爲 時,即使新值與屬性當前的 值相同,也會調用屬性觀察者。
有willSet
和didSet
財產觀察員:
willSet被稱爲值存儲之前。
didSet在新值被存儲後立即調用。
解決你的問題,你可以做這樣的事情:
var myProperty:Int = 0 {
willSet {
print("About to set myProperty, newValue = \(newValue)")
}
didSet{
print("myProperty is now \(myProperty). Previous value was \(oldValue)")
}
}
您可以實現一個或兩個你的財產屬性觀察員。
getter和setter
作爲替代,您可以使用一個存儲的屬性getter和setter方法來解決問題:
private var priv_property:Int = 0
var myProperty:Int{
get {
return priv_property
}
set {
priv_property = newValue
}
}
計算屬性不實際存儲的值。相反,他們提供了一個getter和一個可選的setter來間接檢索和設置其他屬性和值。
你應該使用觀察者或回調。閱讀下面的評論,看看@ 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!")
}
}
}
請問您能解釋一下嗎? bool_的這個值是什麼?它是同一個班級還是別的什麼? – ziya