Sanghyuk's Dev

[Swift] Loops

iOS/Swift2018. 5. 23. 17:15


※ For-In Loops

for item in items {
    code
}
for index in 1...4 {
    print("\(index) times 5 is \(index * 5)")
}


- Wildcard Pattern

for _ in 0...3 {
    print("hello")
}


※ While Loops

조건이 거짓이 될 때까지 일련의 명령문을 수행한다.

첫 번째 반복이 시작되기 전에 반복 횟수를 알지 못할 때 많이 사용한다.

while condition {
    code
}

루프를 통과하는 각 패스의 시작부분에서 조건을 평가한다.


- while

var num = 0
var sum = 0

while num <= 100 {
    sum += num
    num += 1
}

sum


- repeat while

루프를 통과하는 각 패스의 끝 부분에서 조건을 평가한다.

다른 언어에서는 do - while 문으로 많이 사용한다.

num = 0
sum = 0

repeat {
    sum += num
    num += 1
} while num <= 100

sum


'iOS > Swift' 카테고리의 다른 글

[Swift] Control Transfer Statement  (0) 2018.05.23
[Swift] Tuples  (0) 2018.05.23
[Swift] Conditional Statements  (0) 2018.05.23
[Swift] Function  (0) 2018.05.18
[Swift] Basic Operators  (0) 2018.05.17