简体   繁体   中英

Count number of repeats in Swift

I want to know how am I supposed to count the number of time a loop has repeated itself? More specifically how do I extract and output the number of repeats?

var x = 20
while x < 100 {
x += 10
}

The loop has executed 8 times in order to get x == 100. Is there a way to extract the number '8' so it can be used somewhere else (eg to make it a variable elsewhere)?

You said it yourself: you want to count. So count!

var x = 20
var numtimes = 0
while x < 100 {
    x += 10
    numtimes += 1 // count!
}
numtimes // 8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM