5-4. 제어 변경 구문

🌈 devleeky16498·2022년 4월 12일
0

제어 변경 구문은 한 코드에서 다른 코드로 제어를 변경해서 코드가 실행되는 순서를 ㅂ녀경한다. 스위프트에서는 5개의 제어변경을 제공한다.
1. continue
2. break
3. fallthrough
4. return
5. throw

continue

continue구문은 루프를 루프를 통해 다음 반복을 시작하려고 멈추기 위해 부른다. 이것은 루프를 완전히 벗어나지 않고 "현재의 루프는 완료되었다" 라는 의미를 전달한다.

let puzzleInput = "great minds think alike"
var puzzleOutput = ""
let charactersToRemove : [Character] = ["a", "e", "i", "o", "u"]
for character in puzzleInput {
	if charactersToRemove.contains(character) {
    	continue
    }
    puzzleOutput.append(character)
}
print(puzzleOutput)
//다음의 코드는 위의 모든 모음 알파벳을 뺀 문자리터럴을 출력한다 "grtmndsthnklk" 조건을 만족하는 경우 해당 루프를 생략하고 다음 루프로 넘어가게 된다.

break

break구문은 전체 제어흐름 구문을 즉시 종료한다. 이는 switch 내부나 루프 구문에서 switch 또는 루프 구문을 종료할 때 사용될 수 있다.

  1. switch 구문에서 이를 사용할 때 break는 switch구문을 즉시 종료하고 제어를 switch구문의 닫힌 중괄호 다음으로 이동시킨다. 쉽게 이야기하면 switch 구문을 나가고 다음 코드를 실행한다.

let numberSymbol : character = "삼"
var possibleIntegerValue : Int?

switch numberSymbol {
	case "일", "1":
    	possibleIntegerValue = 1
    case "이", "2":
    	possibleIntegerValue = 2
    case "삼", "3":
    	possibleIntegerValue = 3
    default: 
    	break
}

if let integer = possibleIntegerValue {
	print(integer)
} else {
	print("no integerValue")
}
//다음과 같은 경우 possibleIntegerValue = 3이 되며, 3을 출력하게 된다. 
//만약 다른 값을 가지게 되어 default 케이스를 실행하는 경우엔 switch구문을 나오게 된다.

fallthrough

스위프트에서 switch 구문은 각 케이스 맨 아래에서 다음 케이스로 넘어가지 않는다. 첫 케이스가 일치하자마자 switch 구문의 실행은 완료된다.

let integerToDescribe = 5
var description = "The. number \(integertoDescribe) is"

switch integerToDescribe {
	case 2, 3, 5, 7, 11, 13, 17, 19:
    	description += "a prime number, and also"
        fallthough
    default:
    	description += "an integer"
}

print(description)
//이 구문은 The number 5 is a prime number, and also an integer
//fallthrough구문은 만족하는 케이스와 더불어 
//default로 설정한 코드를 무조건 실행하고 switch 구문을 종료한다.

이른 종료(guard)

if 구문과 같이 guard 구문은 표현식의 부울 값에 따라서 구문을 실행한다. guard구문은 다음을 실행하기 위해서 반드시 조건이 참인 것을 요구하기 위해 사용한다. if구문과 반대로 guard 구문은 항상 else 절을 가지고 있다. 참이 아닌 경우 실행된다.

func greet(person : [String: String] {
	guard let name = person["name"] else { return }
    print(name)
    
    guard let location = person["location"] else {
    	print("I hope the weather is nice near you")
        return
    }
    print("I hope the weather is nice in \(location)")

greet(person: ["name" : "John"])
//다음과 같은 경우 name은 존재하나 location의 값은 없으므로 이름을 출력하고 
//"I hope the weather is nice near you"를 출력하게 된다.

greet(person: ["name : "Jane", "location: Cupertino"]
//다음과 같은 경우는 장소도 존재하므로 장소값이 들어간 출력을 실행하게 된다.

guard구문의 조건이 충족되면 코드 실행은 guard 구문의 닫는 중괄호 다음으로 이어지게 된다. 조건의 일부로 옵셔널 바인딩을 사용하면 할당된 상수와 변수를 guard문이 존재하는 나머지 코드 블럭에서 사용 가능하다. 코드블럭의 종료를 위해서 제어를 이동할 수 있으며, return / break / continue / throw 등의 되돌아가지 않는 메서드 같은 구문으로 제어 이동이 가능하다.

profile
Welcome to Growing iOS developer's Blog! Enjoy!🔥

0개의 댓글