Swift Precondition 預處理


前言

  • preconditionassert 的格式類似,也是動態的,precondition 會造成程序的提前終止並拋出錯誤信息。

1、Precondition

  • precondition 在一般的代碼中並不多見,因為它是動態的,只會在程序運行時進行檢查,適用於哪些無法在編譯期確定的風險情況。
    • 如果出現了諸如數據錯誤的情況,precondition 會提前終止程序,避免因數據錯誤造成更多的損失。

    • 如果條件判斷為 true,代碼運行會繼續進行。

    • 如果條件判斷為 false,程序將終止。

    • assert 是單純地觸發斷言即停止程序,不會讓你有機會將可能出錯的設計走過它這一關。

1.1 Precondition 的定義

  • 標准的斷言格式

    precondition(condition: Bool, message: String)
    
    • condition 判斷條件,message 自定義調試信息,斷言中的調試信息參數是可選的。
  • 定義

    public func precondition(_ condition: @autoclosure () -> Bool,
                               _ message: @autoclosure () -> String = default,
                                    file: StaticString = #file,
                                    line: UInt = #line)
    
    public func preconditionFailure(_ message: @autoclosure () -> String = default,
                                         file: StaticString = #file,
                                         line: UInt = #line) -> Never
    

1.2 Precondition 的使用

  • Swift 數組的下標操作可能造成越界,使用擴展的方式向其中增加一個方法來判斷下標是否越界。

    extension Array {
    
        func isOutOfBounds(index: Int) {
        
            precondition((0..<endIndex).contains(index), "數組越界")
        
            print("繼續執行")
        }
    }
    
    // 不越界的情況
    
    [1, 2, 3].isOutOfBounds(index: 2)           // 繼續執行
    
    // 越界的情況
    
    [1, 2, 3].isOutOfBounds(index: 3)           // Thread 1: Precondition failed: 數組越界
    
    • 在滿足 precondition 條件的時候,程序會繼續執行。
    • 在不滿足 precondition 條件的時候,程序被終止,並且將 precondition 中預設的錯誤信息打印到了控制台上,precondition 避免了一些無意義的操作。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM