[Swift] 13. assert와 guard

Hoojeong Kim·2022년 3월 9일
0

Swift Base

목록 보기
15/22
post-thumbnail

assert

assert 는 특정 조건을 체크하고, 조건이 성립되지 않으면 메세지를 출력하게 할 수 있는 함수이다. assert는 디버깅 모드에서만 동작하고, 주로 디버깅 중 조건의 검증을 위해 사용한다.

var value = 0
assert(value == 0)

value = 2
assert(value == 0, "값이 0이 아닙니다.")
__lldb_expr_14/MyPlayground.playground:7: Assertion failed: 값이 0이 아닙니다.
Playground execution failed:

error: Execution was interrupted, reason: EXC_BREAKPOINT (code=1, subcode=0x18f4939c0).
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.

* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BREAKPOINT (code=1, subcode=0x18f4939c0)
  * frame #0: 0x000000018f4939c0 libswiftCore.dylib`Swift._assertionFailure(_: Swift.StaticString, _: Swift.String, file: Swift.StaticString, line: Swift.UInt, flags: Swift.UInt32) -> Swift.Never + 300
    frame #1: 0x000000010055c534 $__lldb_expr15`main at MyPlayground.playground:0
    frame #2: 0x00000001001174f0 MyPlayground`linkResources + 264
    frame #3: 0x0000000180350030 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 20
    frame #4: 0x000000018034f2f4 CoreFoundation`__CFRunLoopDoBlocks + 408
    frame #5: 0x0000000180349bb0 CoreFoundation`__CFRunLoopRun + 764
    frame #6: 0x00000001803493a8 CoreFoundation`CFRunLoopRunSpecific + 572
    frame #7: 0x000000018c03c5ec GraphicsServices`GSEventRunModal + 160
    frame #8: 0x0000000184d937ac UIKitCore`-[UIApplication _run] + 992
    frame #9: 0x0000000184d982e8 UIKitCore`UIApplicationMain + 112
    frame #10: 0x00000001001175b0 MyPlayground`main + 192
    frame #11: 0x00000001003edca0 dyld_sim`start_sim + 20
    frame #12: 0x00000001002350f4 dyld`start + 520

결과를 보면, 첫 번째 assert 구문은 value가 0으로 조건을 성립했으나, 두 번째 assert 구문은 value가 2로, 0이 아니기 때문에 에러를 출력한다.

guard

guard 문은 잘못된 값이 함수에 들어오는 것을 방지하기 위해 사용한다. 조건이 true일 때 guard 뒤에 따라 붙는 코드가 실행된다. 반대로 false일 때는 else문이 실행된다. assert와 달리, 디버깅 모드 뿐만이 아니라 어떤 조건에서도 동작한다.


사용 방법은 다음과 같다.
guard 조건(Bool 타입) else {
	예외사항 실행문
    제어문 전환 명령어
}

이때 guard의 else 블럭 내부에는 종료 지시어인 returnbreak 등이 있어야 한다.


func guardTest(value: Int) {
	guard value == 0 else {return}
    print("Hi!")
}

guardTest(value: 2)
guardTest(value: 0)
Hi!

value가 2일 때는 guard문에서 조건이 false이므로 print문이 실행되지 않았으나, value가 0일 때는 true이므로 Hi!가 출력되었다.

profile
나 애기 개발자 👶🏻

0개의 댓글