본문 바로가기

Swift

for loop in swift

스위프트의 for 구문 : 역순 루프도 참고하시라.

스위프트 공식 홈피에 있는 글인데 검색이 잘 안 되서리 퍼왔다.


Even though Swift has several idiomatic loop options, C-style for loops were still part of the language and occasionally used. For example:

for var i = 0; i < 10; i++ {
    print(i)
}

These have been deprecated in Swift 2.2 and will be removed entirely in Swift 3.0 — one more step towards never typing a semi-colon again.

If you use Xcode, you may be offered a Fix-it that will convert your C-style for loops into modern Swift. In the previous case, the result uses a range like this:

for i in 0 ..< 10 {
    print(i)
}

However, Fix-it’s capabilities are limited, so you will need to do some work yourself. For example, the two loops below are ones that Fix-it will not help you with at this time:

for var i = 10; i > 0; i-- {
    print(i)
}

for var i = 0; i < 10; i += 2 {
    print(i)
}

In the first case, you should create a reverse range using (1...10).reverse(). This is not the same as writing i in 10...1, which will compile but crash at runtime. In the second case, you should use stride(to:by:) to count in twos. So, the correct way to rewrite both loops for Swift 2.2 is like this:

for i in (1...10).reverse() {
    print(i)
}

for i in 0.stride(to: 10, by: 2) {
    print(i)
}

For more information, see the Swift Evolution proposal or read the swift-evolution-announce post detailing the rationale.