반응형
Swift는 반복문을 돌리기 위해 유용한 stride()라는 옵션을 제공한다. stride()는 임의의 증가값을 사용해 시작값에서 최종값으로 이동할 수 있게 한다.
사용법
// to: 옵션은 to 값 포함 하지 않음
for i in stride(from: , to: , by: ) {
print(i)
}
// through: 옵션은 through 값 포함
for i in stride(from: , through: , by: ) {
print(i)
}
사용 예시 - 1(정수 증가)
for i in stride(from: 0, to: 10, by: 2) {
print(i)
}
// output
// 0
// 2
// 4
// 6
// 8
사용 예시 - 2(실수 증가)
for i in stride(from: 0, to: 0.5, by: 0.1) {
print(i)
}
// output
// 0.0
// 0.1
// 0.2
// 0.30000000000000004 (?)
// 0.4
사용 예시 - 3(through 옵션)
for i in stride(from: 0, through: 10, by: 2) {
print(i)
}
// output
// 0
// 2
// 4
// 6
// 8
// 10
사용 예시 - 4(감소)
for i in stride(from: 10, through: 0, by: -2) {
print(i)
}
// output
// 10
// 8
// 6
// 4
// 2
// 0
그렇다면 딱 떨어지지 않는 값으로 증가 혹은 감소를 한다면 ?
for i in stride(from: 10, through: 0, by: -2.3) {
print(i)
}
// output
// 7.7
// 5.4
// 3.1000000000000005
// 0.8000000000000007
마지막 값이 가장 가까운 값으로 줄어들고 루프를 종료한다.
반응형
'Apple > Swift' 카테고리의 다른 글
Swift 07 - 옵셔널(Optional) (0) | 2022.03.13 |
---|---|
Swift 06 - 익스텐션(extension) (0) | 2022.03.12 |
Swift 05 - 프로토콜(Protocol) (0) | 2022.03.12 |
Swift 04 - 클래스(class) (0) | 2022.03.12 |
Swift 03 - 구조체(struct) (0) | 2022.03.12 |