본문 바로가기

Dev/iOS & SWIFT

[Swift] 조건문과 반복문 | 조건문 | if-else | switch | 반복문 | for-in | while | repeat-while

728x90
반응형

조건문

  • 조건에 부합하는지 여부에 따라서 흐름을 처리하는 것!
  • 대표적으로 if-else와 switch가 있음
  • 조건이 들어가는 부분에는 항상 최종적으로 true/false 등의 bool 타입의 값이 들어와야 함
// if-else의 기본적인 형태
if 조건 {
	구현부
} else if 조건 {
	구현부
} else {
	구현부
}

// example
if someInt < 100 {
	print("100 미만")
} else if someInt > 100 {
	print("100 초과")
} else {
	print("100")
}
// case 옆 조건문에 정수 외에도 대부분의 기본 타입을 사용할 수 있음
// default 구문을 꼭 작성해주어야 함
// 명시적으로 break를 해주지 않아도 무조건 걸림
// break를 사용하지 않은 것처럼 하려면 fallthrough를 적어주면 됨
// 여러가지 조건은 , 로 연결해주어도 됨

switch someInt {
case 0:
	print("zero")
case 1..<100: // 범위연산자 (.. 두개면 미만 또는 초과)
	print("1~99:)
case 100:
	print("100")
case 101...Int.max: // 범위연산자 (... 세개면 이하 또는 이상)
	print("over 100")
default:
	print("unknown")
}

반복문

  • 조건에 따라서 반복을 수행하는 구문
  • 대표적으로 for-in, while, repeat-while 등이 있음
  • 주로 collection 타입 (array 등)과 자주 같이 사용됨
// for-in 구문의 기본형태
for item in items {
	code
}

// example-1
for integer in integers {
	print(integer)
}

// example-2
// Dictionary의 item은 key와 value로 구성된 튜플 타입으로 들어옴
for (name, age) in people {
	print("\(name): \(age)")
}
// while의 기본 형태
while condition {
	code
}

// example-1
while integers.count > 1 {
	integers.removeLast()
}

// example-2 : repeat-while
// 타 언어의 do while과 유사 - 스위프트에서 do는 오류처리에서 사용됨
// 구현부 내부를 먼저 1번 실행하고, 조건을 점검
repeat {
	integers.removeLst()
} while integers.count > 0

 

본 내용은 부스트코스의 'iOS 프로그래밍을 위한 스위프트 기초' 강의를 토대로 작성되었습니다

728x90
반응형