ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Assertions & Preconditions
    Swift/Swift Language 2021. 11. 24. 18:13

    Assertions and Preconditions

    Assertions 와 precondins 는 runtime 시 일어나는 확인작업이다. 코드를 더 실행하기 전에 필수 조건을 만족하는지 먼저 확인하기 위해 사용한다. 만약 assertion 이나 precondition 의 Boolean condition 이 true 라면 코드는 평상시와 같이 계속 진행된다. 그러나 그렇지 않은 경우, 코드 실행이 종료되고, 앱도 종료된다(terminated). 코딩 도중 본인이 가정하거나 예상하는 것을 확인하기 위해 이것들을 사용할 수 있다. Assertions 는 실수 또는 잘못된 가정을 개발 도중 확인 하는 데에, preconditions 는 production 에서 발생하는 문제들을 찾는 데에 사용할 수 있다.  

    Runtime 시에 예상하는 것을 확인 하는 데에 뿐만 아니라, assertions 와 preconditions 는 code 내에서 유용한 form of documentation 또한 될 수 있다. Error Handling 에서의 Error conditions 와는 달리, 이것들은 예상되거나 고쳐질 수 있는 errors 에 사용되지 않는다. Failed assertion or precondition 은 유효하지 않은 program state 를 나타내기 때문에, failed assertion 을 catch 할 방법은 없다. 

    Assertions 와 preconditions 를 사용하는 것은 invalid conditions 가 일어나지 않도록 하기 위한 대체수단이 아니다. 이것들을 data 와 state 가 유효하도록 강제시키는 데에 사용하면 invalid state 가 발생했을 때 앱이 종료되도록 할 수 있으므로 debug 를 더 편하게 할 수 있다. invalid state 를 발견하자마자 실행을 멈추면 그에 따른 damage 를 줄이는 것에도 도움이 된다. 

    Assertions 와 preconditions 의 차이는 '언제' 확인하는지에 따라 나뉜다. Assertions 는 builds 를 debug 하는 데에만 사용되지만 preconditions 는 debug 와 production builds 에 모두 쓰인다. Production builds 에서 assertion 내에 있는 condition 은 확인되지 않는다. 따라서 production 의 performance 에는 영향을 주지 않는 assertions 를 개발 과정에서 많이 사용해도 된다. 

     
     

     

    Debugging with Assertions

    Swift standard library 의 assert(_:_:file:line:) function 을 사용해서 assertion 을 작성할 수 있다. True 또는 false 가 결과로 나오는 expression 과 expression 이 false 일 경우 출력할 message 를 function 에 넣어서 사용하면 된다. 

    let age = -3
    
    assert(age >= 0, "A person's age can't be less than zero.")
    // Assertion failed: A person's age can't be less than zero.

     

    위 예시에서 만약 'age >= 0' 이 true 가 될 경우 code 는 계속하여 진행하게 된다. 만약 age 가 위 코드에서와 같이 음수이면 'age >= 0' 은 false 가 되고 assertion 은 fail, 앱은 종료된다. Assertion message 는 생략해도 된다. 

    assert(age >= 0)
     
    만약 code 에서 condition 을 이미 확인했다면, assertionFailure(_:file:line:) function 을 사용해서 assertion failure 을 나타나게 할수도 있다. 
    if age > 10 {
        print("You can ride the roller-coaster or the ferris wheel.")
    } else if age >= 0 {
        print("You can ride the ferris wheel.")
    } else {
        assertionFailure("A person's age can't be less than zero.")
    }
     

     

    Enforcing Preconditions

    Condition 이 false 일 수도 있지만 true 여야만 하는 경우 precondition 을 사용하면 된다.  예를들어, subscript 가 bounds 내에 있다는 것을 확인할 때, function 이 유효한 값을 받았음을 확인할 때 쓴다. precondition(_:_:file:line:) function 에 true 또는 false 가 결과인 expression 과 false 일 경우 출력할 message 를 넣어서 호출하면 된다. 

    // In the implementation of a subscript...
    precondition(index > 0, "Index must be greater than zero.")
     
    preconditionFailure(_:file:line:) function 을 failure 가 발생했음을 나타내기 위해 사용할 수도 있다 - (예를 들어 만약 switch 에서 valid input data 에 대해서는 모두 처리되었어야 하지만 default case 가 들어온 경우). 

     

    NOTE
    If you compile in unchecked mode (-Ounchecked), preconditions aren’t checked. The compiler assumes that preconditions are always true, and it optimizes your code accordingly. However, the fatalError(_:file:line:) function always halts execution, regardless of optimization settings.
    You can use the fatalError(_:file:line:) function during prototyping and early development to create stubs for functionality that hasn’t been implemented yet, by writing fatalError("Unimplemented") as the stub implementation. Because fatal errors are never optimized out, unlike assertions or preconditions, you can be sure that execution always halts if it encounters a stub implementation.

     

     

    출처: https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html

Designed by Tistory.