[英]Swift - Prevent function from being called twice
My main code is to long to put here so i'll try with a simpler explanation. 我的主要代码要放到这里,所以我将尝试更简单的解释。 Let's say i have a global variable called "count" that gets used by functions.
假设我有一个名为“ count”的全局变量,该变量将被函数使用。 If count was to get called twice for we reason as shown in the code below... how can i make it so the output "10 , 10" rather then "10 , 20".
如果计数由于我们的原因而被调用两次,如下面的代码所示……我该如何使其输出为“ 10,10”而不是“ 10,20”。
var count = 0
override func viewDidLoad() {
helloWorld()
}
override func viewWillAppear(_ animated: Bool) {
helloWorld()
}
func helloWorld(){
var counter = 0
for i in 1...10{
count = count + 1
counter = counter + 1
}
print(count)
}
Use DispatchQueue with static token (cached through app lifecycle), here's a useful extension: 将DispatchQueue与静态令牌(通过应用程序生命周期缓存)一起使用,这是一个有用的扩展:
extension DispatchQueue {
private static var tokens: [String] = [] // static, so tokens are cached
class func once(executionToken: String, _ closure: () -> Void) {
// objc_sync_enter/objc_sync_exit is a locking mechanism
objc_sync_enter(self)
defer { objc_sync_exit(self) }
// if we previously stored token then do nothing
if tokens.contains(executionToken) { return }
tokens.append(executionToken)
closure()
}
}
func doSomething() {
DispatchQueue.once(executionToken: "doSomething") {
print("This should be executed once")
}
}
doSomething()
doSomething()
doSomething()
"This should be executed once" will be printed only once. “这应该执行一次”将仅打印一次。
You can also use the lazy mechanism: 您还可以使用惰性机制:
class SomeClass {
lazy var executeOnce: () -> Void = {
doSomething()
return {}
}()
func doSomething() {
print("This should be executed once")
}
}
let someClass = SomeClass()
someClass.executeOnce()
someClass.executeOnce()
someClass.executeOnce()
It's thread-safe out of the box so you don't need to worry about locking. 它是线程安全的开箱即用,因此您无需担心锁定。
Change 更改
func helloWorld(){
var counter = 0
for i in 1...10{
count = count + 1
counter = counter + 1
}
print(count)
}
to 至
func helloWorld(){
var counter = self.count
for i in 1...10{
count = count + 1
}
print(count)
self.count = counter
}
This way you store into counter the count value before it changes, then make it equal to the previous one again. 这样,您可以在计数值更改之前将其存储到计数器中,然后再次使其等于前一个值。
NOTE: This way you will always get 10 when you call helloWorld(), no matter how much time you call the function.
注意:这样,无论调用该函数多少时间,调用helloWorld()都将始终获得10。
You can change the function as shown below: 您可以如下所示更改功能:
func helloWorld(_ countValue: Int){
var counter = self.count
for i in 1..<countValue{
count = count + 1
}
print(count)
self.count = counter
} }
So you can choose the upper element of the counter simply by calling: 因此,您只需调用以下命令即可选择计数器的上层元素:
helloWorld(10)
helloWorld(20)
ADVICE: it's not a good practice to have a function that changes an external value
建议:拥有改变外部价值的功能不是一个好习惯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.