Swift iOS - 如何在循环中的循环完成后执行完成

Swift iOS -How to execute a completion after a loop within a loop has finished

我在另一个循环中有一个循环,我希望内部循环在两个循环都完成后 运行 完成块。

内循环和完成:

func runThenPrint(_ count: Int, completion:()->()){
    for num in 0..<(count){
        print(num)
    }
    completion()
}

func imDone(){
    print("DONE")
}

具有内部和完成的外部循环:

//outer
for num in 0..<5{
    //inner
    runThenPrint(num){imDone}
}

在 Playgrounds 中我得到:

DONE
0
DONE
0
1
DONE
0
1
2
DONE
0
1
2
3
DONE

但我想要:

0
1
2
3
4
DONE

我查看了这个 post 但它基于 1 个循环而不是循环中的循环。我还在群组中找到了其他 post,但它们基于网络调用。

将此内容发送到 运行 的最佳方法是什么?

你得到的是完全正常的。请记住,for 循环会重复调用。所以 for num in 0..<5 会变成 运行 4 次。第一次,num为0,所以

for num in 0..<(count)){
        print(num)
}

不打印任何内容,然后立即调用完成处理程序,打印 "DONE"。第二次,num 为 1,因此内部 for 循环将 运行 1 次并打印 0,然后打印 "DONE" 依此类推。

可以使用

实现所需的输出
runThenPrint(5, completion: imDone)

因为您只希望 'inner' for 循环 运行 5 次。