类似于延迟:
var sumOfOdd = 0
for i in 0...10 {
defer {
print("Look! It's \(i)---\(sumOfOdd)")
}
if i % 2 == 0 {
continue
}
sumOfOdd += i
}
打印结果:
Look! It's 0---0
Look! It's 1---1
Look! It's 2---1
Look! It's 3---4
Look! It's 4---4
Look! It's 5---9
Look! It's 6---9
Look! It's 7---16
Look! It's 8---16
Look! It's 9---25
Look! It's 10---25
想要某部分代码延迟到作用域结束后执行,defer是个很好的选择
网友评论