我试图在地图上绘制位置,在每个绘制位置之间一个接一个地绘制1秒,但它不能正常工作。这就是我到目前为止所拥有的:
@IBAction func playButtonPressed(_ sender: Any) {
var index = 0.0
var i = 0
var j = 0
while i < sites.count {
while j < sites[i].count {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0*index) {
self.plot(day:i,site:j)
}
j += 1
index += 1
}
j = 0
i += 1
}
}
func plot(day:Int,site:Int) {
for letter in glossary {
let siteToPlot = sites[day][site]
if let location = letter[siteToPlot] {
setUpMap(name: location.name!, lat: location.lat!, long: location.long!)
}
}
}
我设置的方式,for循环中的每个项目都有一个在DispatchQueue.main.asyncAfter中调用的方法,但是每个项目将在一秒后调度。首先是0秒后,然后是1,然后是2,等等。
似乎没有保存绘图函数参数,但是,当第一次调用绘图函数时,日期和站点值为9和0,这是循环结束时的值。 / p>
答案 0 :(得分:2)
您可以通过创建局部变量来解决此问题:
@IBAction func playButtonPressed(_ sender: Any) {
var index = 0.0
var i = 0
var j = 0
while i < sites.count {
while j < sites[i].count {
let day = i
let site = j
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0 * index) {
self.plot(day: day, site: site)
}
j += 1
index += 1
}
j = 0
i += 1
}
}
或者,如Martin R在Pass value to closure?中指出的那样,你可以&#34;捕获&#34;这些变量:
@IBAction func playButtonPressed(_ sender: Any) {
var index = 0.0
var i = 0
var j = 0
while i < sites.count {
while j < sites[i].count {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0 * index) { [i, j] in
self.plot(day: i, site: j)
}
j += 1
index += 1
}
j = 0
i += 1
}
}
或者,就个人而言,我可能会使用for
循环来清理这一点:
@IBAction func playButtonPressed(_ sender: Any) {
var delay = 0.0
for i in 0 ..< sites.count {
for j in 0 ..< sites[i].count {
DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [i, j] in
self.plot(day: i, site: j)
}
delay += 1
}
}
}