美文网首页
swift precondition 强制先决条件

swift precondition 强制先决条件

作者: json_jie | 来源:发表于2017-09-12 17:59 被阅读92次

precondition(::file:line:) 函数


代码中任何条件可能潜在为假但必须肯定为真才能继续执行的地方使用先决条件

precondition(::file:line:) 函数来写先决条件。给这个函数传入表达式计算为 true 或 false ,如果条件的结果是 false 信息就会显示出来

func toBool(x: Int) -> Bool {
    precondition(x == 0 || x == 1, "This function can only convert 0 or 1 to Bool")
    if x == 0 {
        return false
    }
    /* x == 1 */
    return true
}
toBool(x: 1)
toBool(x: 0)

**
toBool(x: 1) = true
toBool(x: 0) = false
**


toBool(x: 2)
会报错:error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

log打印:precondition failed: This function can only convert 0 or 1 to Bool: file Swift4-9.12.playground, line 159

相关文章

网友评论

      本文标题:swift precondition 强制先决条件

      本文链接:https://www.haomeiwen.com/subject/pathsxtx.html