[Swift] Assert랑 Precondition

코르피·2023년 1월 5일

Assertions and Preconditions

Assertion
개발 중에 실수와 잘못된 가정을 찾는데 도움이 된다.

Preconditions
상품에서 이슈를 찾는데 도움이 된다.

assertion과 precondition은 잘못된 프로그램 상태를 잡는데 도움이된다.

Assertion, precondition은 실패할 경우 catch할 수 없다. (무조건 터진다)

사용법

assert(::file:line:) 사용법

Condition : 조건문
Message : false시 출력할 문구
File: cmd창에 띄울 파일 명. 보통 #file
Line: cmd창에 띄울 라인 넘버. 보통 #line

assertionFailure(_:file:line:) 사용법

같은데 항상 fail이라 얘 만나면 무조건 터지는 거임

precondition은 번역해보면 false일 가능성이 있을 때 사용. 근데 계속 실행되려면 true 여야함. 이라고 적혀있음
assert랑 똑같이 터짐. 몬 차이?

preconditionFailure도 assert처럼 똑같이 사용함

출력

File, line 넣은 것
2023-01-05 22:41:07.496599+0900 JuiceMaker[97082:3487274] /Users/ijeongmin/Desktop/yagom/careerStarter/3. 쥬스 메이커/ios-juice-maker/JuiceMaker/JuiceMaker/Model/FruitStore.swift:22: Fatal error: 일부러 터뜨리기

File 만
2023-01-05 22:40:16.567785+0900 JuiceMaker[96974:3484796] /Users/ijeongmin/Desktop/yagom/careerStarter/3. 쥬스 메이커/ios-juice-maker/JuiceMaker/JuiceMaker/Model/FruitStore.swift:22: Fatal error: 일부러 터뜨리기

Line 만
2023-01-05 22:40:45.805291+0900 JuiceMaker[97037:3486214] JuiceMaker/FruitStore.swift:22: Fatal error: 일부러 터뜨리기

근데 왜 둘다 넣은거랑 file만 넣은거 나오는게 같냐..

차이

두개의 차이는
assert는 debug build에서만 체크되고
Precondition은 debug build랑 production build에서 둘다 체크된다고 한다.
시뮬레이션에서는 둘 다 되는 것 같은데 실제 앱에서는 assert는 안나온다는 얘기?

실물 폰에 다운받아서 실행해보면 둘다 터짐.
production은 그럼 실제 배포라는 얘기?

프로젝트 파일 -> build settings -> Swift Compiler -> Optimization level
을 -O로 바꿨더니 assert 체크를 안함. 오! bebug랑 release가 있었음
-Ounchecked가 어쩌고 하는 거랑 체크 안하는거 몇개 더 있는 것 같음.
그냥 release 디폴트 값으로 하면 될듯 뭔 차인지 몰?루

precondition을 입력하면 자동입력으로 밑에 나오는 dispatchPrecondition이 있는데
얘는 DispatchQueue를 사용할 때 어떤 큐 인지 체크하기 위함. 다른거임

let queue = DispatchQueue.global()
let mainQueue = DispatchQueue.main
        
mainQueue.async {
    dispatchPrecondition(condition: .notOnQueue(mainQueue)) // mainQueue가 아니라고 예상함. 근데 mainQueue라서 죽음..
        print("mainQueue")
    }
        
queue.async {
    dispatchPrecondition(condition: .onQueue(queue))
        // 정상 실행
        print("globalQueue")
    }

이런거. 근데 웃긴건 dispatchAssert는 없음 ㅋ

profile
행복합시다!!

0개의 댓글