Swift - 斷言和前提條件



Swift 提供了兩種特殊的機制:斷言和前提條件,允許開發者在程式中強制執行一些特殊條件,用於除錯和確保程式的正確性。這兩種方法透過捕獲和處理應用程式開發不同階段出現的意外情況,建立健壯可靠的 Swift 應用程式。

Swift 斷言

斷言是一個強大的除錯工具,用於檢查和修復應用程式開發過程中的錯誤或bug。或者可以說,其主要目的是在執行時捕獲和識別錯誤或bug。它用布林條件表示,如果條件計算結果為真,則程式將繼續執行。而如果條件計算結果為假,則程式的執行將終止。斷言是不可恢復的,這意味著如果斷言失敗,我們無法恢復或捕獲它。我們可以使用 `assert()` 函式實現斷言。

**`assert(_:_:file:line)`** 函式在開發期間執行執行時檢查。或者可以說,它實現了 C 風格的斷言。

語法

以下是 `assert()` 函式的語法:

func assert(_condition: @autoclosure()->Bool,
_message: @autoclosure() -> String = String(),
file: StaticString = #file,
line: UInt = #line)

引數

此函式採用以下引數:

  • **`condition`** - 它表示測試條件。

  • **`message`** - 它表示當條件設定為假時將顯示的訊息。預設值為為空。

  • **`file`** - 它表示斷言所在的檔名,如果斷言失敗,則會與訊息一起顯示。這是一個可選引數。

  • **`line`** - 它表示斷言所在的行號,如果斷言失敗,則會與訊息一起顯示。這是一個可選引數。

示例

import Foundation

func validateMarks(_ marks: Int) {

   // Assert that the marks is non-negative
   // If the given condition fails, then the program will terminated 
   // And will display this message
   assert(marks >= 0, "Marks must be non-negative value")
    
   print("Marks are valid")
}
validateMarks(345)

輸出

Marks are valid

示例

如果我們輸入負數分數,則斷言中的給定條件將失敗,程式將終止。

import Foundation

func validateMarks(_ marks: Int) {

   // Assert that the marks is non-negative
   // If the given condition fails, then the program will terminated 
   // And will display this message
   assert(marks >= 0, "Marks must be non-negative value")
    
   print("Marks are valid")
}
validateMarks(-39)

輸出

main/main.swift:8: Assertion failed: Marks must be non-negative value
Current stack trace:
0    libswiftCore.so                    0x00007f8870bbcdc0 _swift_stdlib_reportFatalErrorInFile + 112
1    libswiftCore.so                    0x00007f887088691c <unavailable> + 1444124
2    libswiftCore.so                    0x00007f8870886738 <unavailable> + 1443640
3    libswiftCore.so                    0x00007f8870885220 _assertionFailure(_:_:file:line:flags:) + 419
6    swift-frontend                     0x0000557401fc6b3d <unavailable> + 26479421
7    swift-frontend                     0x00005574012fadb9 <unavailable> + 13061561
8    swift-frontend                     0x00005574010cb4c6 <unavailable> + 10769606
9    swift-frontend                     0x00005574010c79b6 <unavailable> + 10754486
.......................................................................
....................................................................
..................................................................

Swift 前提條件

前提條件用於在程式碼執行時捕獲和處理意外狀態和假設。或者可以說,前提條件幫助開發者在應用程式的生產狀態下查詢問題。

它也用布林條件表示,如果條件計算結果為真,則程式將繼續執行。而如果條件計算結果為假,則程式的執行將終止。它也是不可恢復的。我們可以使用 **`precondition()`** 函式實現前提條件。

**`precondition(_:_:file:line)`** 函式用於在程式執行期間強制執行條件。

語法

以下是 `assert()` 函式的語法:

func precondition(_condition: @autoclosure()->Bool,
_message: @autoclosure() -> String = String(),
file: StaticString = #file,
line: UInt = #line)

引數

此函式採用以下引數:

  • **`condition`** - 它表示測試條件。

  • **`message`** - 它表示當條件設定為假時將顯示的訊息。預設值為為空。

  • **`file`** - 它表示前提條件所在的檔名,如果前提條件失敗,則會與訊息一起顯示。這是一個可選引數。

  • **`line`** - 它表示前提條件所在的行號,如果前提條件失敗,則會與訊息一起顯示。這是一個可選引數。

示例

import Foundation

func modulus(_ num: Int, by deno: Int) -> Int {

   // Ensure that the denominator is not zero before performing the modulus
   precondition(deno != 0, "The value of denominator must be non-zero")

   return num % deno
}

let output = modulus(19, by: 3)
print("Result: \(output)")  

輸出

Result: 1

示例

如果我們輸入零分母,則前提條件中的給定條件將失敗,程式將終止。

import Foundation

func modulus(_ num: Int, by deno: Int) -> Int {

   // Ensure that the denominator is not zero before performing the modulus
   precondition(deno != 0, "The value of denominator must be non-zero")

   return num % deno
}

let output = modulus(19, by: 0)
print("Result: \(output)")  

輸出

main/main.swift:6: Precondition failed: The value of denominator must be non-zero
Current stack trace:
0    libswiftCore.so                    0x00007fbee7245dc0 _swift_stdlib_reportFatalErrorInFile + 112
1    libswiftCore.so                    0x00007fbee6f0f91c <unavailable> + 1444124
2    libswiftCore.so                    0x00007fbee6f0f738 <unavailable> + 1443640
3    libswiftCore.so                    0x00007fbee6f0e220 _assertionFailure(_:_:file:line:flags:) + 419
6    swift-frontend                     0x0000558e85a69b3d <unavailable> + 26479421
7    swift-frontend                     0x0000558e84d9ddb9 <unavailable> + 13061561
8    swift-frontend                     0x0000558e84b6e4c6 <unavailable> + 10769606
9    swift-frontend                     0x0000558e84b6a9b6 <unavailable> + 10754486
.......................................................................
....................................................................
..................................................................
廣告