반복문

JG Ahn·2024년 10월 2일

swift 기초

목록 보기
9/23

1. for-in

  • Java의 for each와 유사
  • Dictionary는 튜플 형식
// 기본 형태
for 변수명 in 배열 {
	/* 실행 구문 */
}
for i in 0 ..< 10 {
	print(i)
}
var integers = [1,2,3]
let people = ["Harry": 30, "Johnson": 22, "Kyle": 30]

for integer in integers {
    print(integer)
}

// Dictionary - key와 value로 구성된 튜플 타입
for (name, age) in people {
    print("\(name): \(age)")
}
  • 상수의 생략 "_"
//만약 루프문 안에서 주어진 상수를 사용하지 않는다면 언더바를 사용
for _ in 0 ..< 10 {
	print("*")
}
  • forEach문 활용
// 위 for-in문과 동일한 결과 출력
people.forEach {(name: String, age: Int) in
	print("\(name): \(age)")
}

// key값만 출력
people.keys.forEach { name in
    print("이름: \(name)")
}

// value값만 출력
people.values.forEach { age in
	print("\(age)")
}

2. while

  • 조건문이 false일 때 반복문을 탈출
// 기본 형태 - 조건의 소괄호 생략 가능
while (조건문) {
	/* 실행 구문 */
}

3. repeat-while

  • Java의 do while과 유사
// 기본 형태
repeat {
	/* 실행 구문 */
} while 조건
repeat {
	integers.removeLast()
} while integers.count > 0

0개의 댓글