Swift Precondition 预处理

前言

  • preconditionassert 的格式类似,也是动态的,precondition 会造成程序的提前终止并抛出错误信息。

1、Precondition

  • precondition 在一般的代码中并不多见,因为它是动态的,只会在程序运行时进行检查,适用于哪些无法在编译期确定的风险情况。

    • 如果出现了诸如数据错误的情况,precondition 会提前终止程序,避免因数据错误造成更多的损失。

    • 如果条件判断为 true,代码运行会继续进行。

    • 如果条件判断为 false,程序将终止。
    • assert 是单纯地触发断言即停止程序,不会让你有机会将可能出错的设计走过它这一关。

1.1 Precondition 的定义

  • 标准的断言格式

    1
    precondition(condition: Bool, message: String)
    • condition 判断条件,message 自定义调试信息,断言中的调试信息参数是可选的。
  • 定义

    1
    2
    3
    4
    5
    6
    7
    8
    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 数组的下标操作可能造成越界,使用扩展的方式向其中增加一个方法来判断下标是否越界。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    extension Array {

    func isOutOfBounds(index: Int) {

    precondition((0..<endIndex).contains(index), "数组越界")

    print("继续执行")
    }
    }
    1
    2
    3
    // 不越界的情况

    [1, 2, 3].isOutOfBounds(index: 2) // 继续执行
    1
    2
    3
    // 越界的情况

    [1, 2, 3].isOutOfBounds(index: 3) // Thread 1: Precondition failed: 数组越界
    • 在满足 precondition 条件的时候,程序会继续执行。
    • 在不满足 precondition 条件的时候,程序被终止,并且将 precondition 中预设的错误信息打印到了控制台上,precondition 避免了一些无意义的操作。
文章目录
  1. 1. 前言
  2. 2. 1、Precondition
    1. 2.1. 1.1 Precondition 的定义
    2. 2.2. 1.2 Precondition 的使用
隐藏目录