[Swift] 제어흐름 (반복문, 제어문, switch)

Soomin Kim·2024년 7월 23일

Swift

목록 보기
7/12
post-thumbnail

반복문

for-in 구문

for-in 반복문은 연속된 일련의 항목들을 반복하는데 사용된다.

for 상수명 in 컬렉션 또는 범위 {
	//실행 코드
}
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
	print("Hello, \(name)!")
}
//출력
//Hello, Anna!
//Hello, Alex!
//Hello, Brian!
//Hello, Jack!

1) 딕셔너리 키-값 쌍 접근을 위해 for-in 반복문 사용
딕셔너리 콘텐츠는 기본적으로 순서가 없으며 반복으로 가져올 아이템에 대한 순서를 보장하지 않는다.

let numberOfLegs = ["spider" : 8, "ant" : 6, "cat" : 4]
for (animalName, legCount) in numberOfLegs {
	print("\(animalNme) have \(legCount) legs")
}
//출력 (순서x)
//cat have 4 legs
//spider have 8 legs
//ant have 6 legs

2) 숫자 범위에 대해 for-in 반복문 사용
닫힌 범위 연산자(...)을 사용하여 숫자 범위 표시한다.

for index in 1...5 {
	print("Value of index is \(index)")
}
//출력
//Value of index is 1
//Value of index is 2
//Value of index is 3
//Value of index is 4
//Value of index is 5

3) 참조체가 필요하지 않다면 밑줄 문자(_)로 대체 가능

var count = 0 

for _ in 1...5 {
	count += 1
}

//count = 15

4) 양 끝점을 포함하는 닫힌 범위를 사용하지 않는 경우

ex ) 시계에 매 분마다 눈금을 그리는 것

  • 0분을 시작으로 1분마다 60개의 눈금
let minutes = 60
for tickMark in 0..<minutes {
	// 0분~60분
}
  • 0분을 시작으로 5분마다 12개의 눈금
    stride(from:to:by:) 함수 사용
let minuteInterval = 5
for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
//5분마다 눈금(0,5,10,15...45,50,55)
}
  • 3시간마다 8개 눈금
    stride(from:to:by:) 함수 사용
let hours = 12
let hourInterval = 3
for tickMark in stride(from: 3, through: hours, by: hourInterval) {
// 3시간마다 8개 눈금 (3,6,9,12)
}

while 반복문

while 반복문은 지정된 조건에 만족할 때까지 일련의 항목들을 반복하는데 사용된다.

while 조건문 {
	//실행 코드
}

조건문 은 true또는 false를 반환하는 표현식이며, //실행코드 는 조건문이 true일 동안에 실행될 코드를 나타낸다.

var myCount = 0

while myCount < 100{
myCount += 1
}

multiplyByTen(value: 5)
multiplyByTen(value: 10)

위 예제에서 while문은 myCount 변수가 100보다 작은지 평가한다.
100보다 작다면 반복문이 계속 실행되고
100보다 크면 괄호 안의 코드를 건너뛰고 반복문을 종료하게 된다.

repeat ... while 반복문

repeat ... while 반복문은 while 반복문을 거꾸로 한 것이다. 반복문 안의 코드가 언제나 적어도 한 번은 실행되야 하는 상황을 위해 사용된다. 다른 언어의 do ... while 반복문과 유사

repeat 
	//실행 코드
} while 조건식

다음 예제는 i라는 이름의 변숫값이 0이 될 때까지 반복된다.

var i = 10

repeat {
	i-=1
} while (i>0)

break 구문

현재 반복문에서 빠져나와 반복문 다음의 코드로 이동하여 실행을 계속하게 한다.

아래의 예제는 j의 값이 100을 넘을 때까지 반복문을 계속 실행하며,
100이 넘으면 반복문을 종료하고 반복문 다음의 코드를 진행한다.

var j = 10
for _ in 0..<100
{
	j+=j
    
    if j>100 {
    break
    }
    
    print("j = \(j)")
}

continue 구문

반복문의 나머지 코드를 건너뛰고 반복문의 처음으로 돌아가게 한다.

다음 예제에서 print 함수는 i 변수의 값이 짝수일 때만 호출된다.
continue 구문이 실행되면 while 반복문의 시작 지점으로 돌아가며, i의 값이 20보다 작다면 다시 반복문을 수행하게 된다.

var i = 1
while i < 20
{
	i += 1
    
    if (i%2) != 0 {
    	continue
    }
    
    print("i = \(i)")
}

조건문

if 구문

if 구문은 조건식이 true면 구문 내의 코드가 실행되고 false이면 구문 내의 코드는 건너뛴다.

if 조건식 {
	//조건식이 true일 때 실행되는 코드
}

괄호{}가 필수적이다.

하나의 값이 다른 값보다 더 큰지에 따라 결정해야하는 경우의 예제

let x = 10

if x > 9 {
	print("x is greater than 9!")
}

if ... else ...구문

변형된 if 구문은 조건식이 false 일 때 수행할 코드를 지정할 수 있게 해준다.

if 조건식 {
	//조건식이 true일 때 실행되는 코드
}
else 조건식 {
	//조건식이 false일 때 실행되는 코드
}

앞의 예제 변형하기

let x = 10

if x > 9 {
	print("x is greater than 9!")
}
else {
	print(""x is less than 9!")
}

if ... else if ... 구문

다양한 조건을 바탕으로 결정해야 할 때 사용한다.

let x = 9

if x == 10 {
	print("x is 10")
}
else if x == 9 {
	print("x is 9")
}
else if x == 8 {
	print("x is 8")
}

guard 구문

guard 구문은 불리언 표현식을 포함하며, ture일 때만 gurad 구문 다음에 위치한 코드가 실행된다.
guard 구문은 불리언 표현식이 false일 때 수행될 else 절을 반드시 포함해야 한다.
else 절의 코드는 현재의 코드에서 빠져나가는 구문 (ex. return, break, continue, throw, 함수, 메서드 등)을 포함해야 한다.

guard <조건문(불리언 표현식)> else {
	//조건문이 false일 때 실행될 코드
	<종료 구문>
}
//조건문이 true일 때 실행될 코드

기본적으로 gurard 구문은 특정 조건을 만족하지 않은 경우에 현재의 함수, 반복문에서 빠져나올 수 있게 해준다.

func multiplyByTen(value: Int?) {
	guard let number = value, number < 10 else {
    print("Number is too high")
    return
    }
    
    let result = number * 10
    print(result)
}

multiplyByTen(value: 5)
multiplyByTen(value: 10)

switch 구문

두 세개 이상의 조건을 만들 때는 코드를 작성하는 시간도 많이 걸릴 뿐만 아니라 읽기도 어려워진다. 이러한 경우 switch 구문은 최고의 대안이 된다.

switch 표현식 {
	case 일치하는 값1:
    	코드 구문
    case 일치하는 값2:
    	코드 구문
    case 일치하는 값3, 일치하는 값4:
    	코드 구문
    default :
    	코드 구문
}

표현식 : 값을 나타내거나 값을 반환하는 표현식
일치하는 값 : '표현식'과 동일한 타입, case 조건과 일치하는 값일 경우 코드구문 실행
default 절 : 표현식과 일치하는 case 구문이 없을 때 실행

switch 구문 예제

let someCharacter: Character = "z"
switch someCharacter {
case "a":
    print("The first letter of the Latin alphabet")
case "z":
    print("The last letter of the Latin alphabet")
default:
    print("Some other character")
}
// 출력 : "The last letter of the Latin alphabet"

case 구문 결합하기

서로 다른 case에 대해 동일한 코드가 실행되어야 하기도 한다.
각각의 일치하는 경우들을 공통으로 실행될 구문과 묶을 수 있다.

let value = 1
switch (value) {
case 0,1,2:
    print("zero, one or two")
case 3:
    print("three")
case 4:
    print("four")
default:
    print("Integer out of range")
}
// 출력 : "zero, one or two"

switch 구문에서 범위 매칭하기

switch 구문 안에 있는 case 구문에 범위 매칭을 구현할 수도 있다.

let approximateCount = 62
let countedThings = "moons orbiting Saturn"
let naturalCount: String
switch approximateCount {
case 0:
    naturalCount = "no"
case 1..<5:
    naturalCount = "a few"
case 5..<12:
    naturalCount = "several"
case 12..<100:
    naturalCount = "dozens of"
case 100..<1000:
    naturalCount = "hundreds of"
default:
    naturalCount = "many"
}
print("There are \(naturalCount) \(countedThings).")
// 출력 : "There are dozens of moons orbiting Saturn."

where 구문

where 구문은 case 구문에 부가적인 조건을 추가하기 위해서 사용된다.
아래의 예제는 값이 범위 조건에 일치하는지 검사하고, 그 숫자가 홀수인지 짝수인지도 검사한다.

let temperature = 54

switch(temperature)
{
	case 0...49 where temperature % 2 == 0:
    	print("cold and even")
    case 50...79 where temperature % 2 == 0:
    	print("warm and even")
    case 80...110 where temperature % 2 == 0:
    	print("hot and even")
    default:
    	print("Temperature out of range or odd")    
}
// 출력 : "warm and even"

fallthrough

swift에서는 case 구문 끝에 break를 쓸 필요가 없다. 왜냐하면 swift는 case 조건에 일치하면 자동으로 구문 밖으로 빠져나가기때문이다.
만약 fallthrough 구문을 사용하면 switch 구문에 예외상황 효과를 주어, 실행 흐름이 그 다음 case 구문으로 계속 진행하게 할 수 있다.

let temperature = 54

switch(temperature)
{
	case 0...49 where temperature % 2 == 0:
    	print("cold and even")
        fallthrough
        
    case 50...79 where temperature % 2 == 0:
    	print("warm and even")
        fallthrough
        
    case 80...110 where temperature % 2 == 0:
    	print("hot and even")
		fallthrough

    default:
    	print("Temperature out of range or odd")    
}

튜플 사용

같은 switch 구문에 여러 값인 튜플을 사용할 수 있다. 가능한 어떠한 값도 일치하도록 언더바 문자 (_)를 사용할 수 있다.

let somePoint = (1, 1)
switch somePoint {
case (0, 0):
    print("\(somePoint) is at the origin")
case (_, 0):
    print("\(somePoint) is on the x-axis")
case (0, _):
    print("\(somePoint) is on the y-axis")
case (-2...2, -2...2):
    print("\(somePoint) is inside the box")
default:
    print("\(somePoint) is outside of the box")
}
// 출력 : "(1, 1) is inside the box"

값 바인딩

switch case에는 일치하는 값 또는 값들을 임시적 상수(변수)로 이름을 가질 수 있으며 케이스 본문 안에서 사용할 수 있다.

let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
    print("on the x-axis with an x value of \(x)")
case (0, let y):
    print("on the y-axis with a y value of \(y)")
case let (x, y):
    print("somewhere else at (\(x), \(y))")
}
// 출력 : "on the x-axis with an x value of 2"

0개의 댓글