我有一个简单的SwiftUI示例,每次计时器启动时,它都会将一个块向下移动X像素;我完整地写出了代码。
这里发布的可以被认为是零;vertiSide+horizSide只是参考数字。
现在这是可行的,但我想在循环中执行它。
fileprivate func extractedFunc() {
let t3 = "(tileP[0 + issued].vertiSide - 32)(tileP[0 + issued].horizSide)"
if let ok = tileD[t3] {
if !ok {
var t0 = "(tileP[0 + issued].vertiSide)(tileP[0 + issued].horizSide)"
tileD[t0] = false
tileP[0 + issued].vertiSide -= 32
var t1 = "(tileP[0 + issued].vertiSide)(tileP[0 + issued].horizSide)"
tileD[t1] = true
t0 = "(tileP[1 + issued].vertiSide)(tileP[1 + issued].horizSide)"
tileD[t0] = false
tileP[1 + issued].vertiSide -= 32
t1 = "(tileP[1 + issued].vertiSide)(tileP[1 + issued].horizSide)"
tileD[t1] = true
t0 = "(tileP[2 + issued].vertiSide)(tileP[2 + issued].horizSide)"
tileD[t0] = false
tileP[2 + issued].vertiSide -= 32
t1 = "(tileP[2 + issued].vertiSide)(tileP[2 + issued].horizSide)"
tileD[t1] = true
t0 = "(tileP[3 + issued].vertiSide)(tileP[3 + issued].horizSide)"
tileD[t0] = false
tileP[3 + issued].vertiSide -= 32
t1 = "(tileP[3 + issued].vertiSide)(tileP[3 + issued].horizSide)"
tileD[t1] = true
}
}
}
所以我写了这个代码,它做了同样的事情[我想]
let semaphore = DispatchSemaphore(value: 1)
DispatchQueue.global().async {
let t3 = "(tileP[0].vertiSide - 32)(tileP[0].horizSide)"
for i in 0..<tileP.count {
semaphore.wait()
if let ok = tileD[t3] {
if !ok {
let t0 = "(tileP[i].vertiSide)(tileP[i].horizSide)"
tileD[t0] = false
tileP[i].vertiSide -= 32
let t1 = "(tileP[i].vertiSide)(tileP[i].horizSide)"
tileD[t1] = true
}
}
semaphore.signal()
}
}
但是输出非常不同,对于版本1,我得到了tileD数组的输出。
Optional(false) 512.00.0
Optional(false) 480.00.0
Optional(false) 448.00.0
Optional(false) 416.00.0
Optional(false) 384.00.0
Optional(false) 352.00.0
Optional(false) 320.00.0
Optional(false) 288.00.0
Optional(false) 256.00.0
Optional(false) 224.00.0
Optional(false) 192.00.0
Optional(false) 160.00.0
Optional(false) 128.00.0
Optional(true) 96.00.0
Optional(true) 64.00.0
Optional(true) 32.00.0
Optional(true) 0.00.0
但对于版本2,我得到的输出
Optional(true) 512.00.0
Optional(true) 480.00.0
Optional(true) 448.00.0
Optional(false) 416.00.0
Optional(false) 384.00.0
Optional(false) 352.00.0
Optional(false) 320.00.0
Optional(false) 288.00.0
Optional(false) 256.00.0
Optional(false) 224.00.0
Optional(false) 192.00.0
Optional(false) 160.00.0
Optional(false) 128.00.0
Optional(false) 96.00.0
Optional(false) 64.00.0
Optional(false) 32.00.0
Optional(true) 0.00.0
就我的一生而言,我看不出有什么不同?我错过了什么??
信号量的作用是什么?代码中没有异步线程内容。
只需写入
fileprivate func extractedFunc() {
let t3 = "(tileP[0 + issued].vertiSide - 32)(tileP[0 + issued].horizSide)"
if let ok = tileD[t3] {
if !ok {
for i in 0..<4 {
let t0 = "(tileP[i + issued].vertiSide)(tileP[i + issued].horizSide)"
tileD[t0] = false
tileP[i + issued].vertiSide -= 32
let t1 = "(tileP[i + issued].vertiSide)(tileP[i + issued].horizSide)"
tileD[t1] = true
}
}
}
}