日志记录、assert/precondition/fatalError
使用 print/debugPrint 记录状态,并根据不变量选择 assert (仅调试模式)、 precondition (发布版本也会检查)或 fatalError (导致崩溃)。
日志记录、assert/precondition/fatalError 是 CoddyKit 上的免费 Swift Academy 课时。 这是第 2 节课,共 2 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Swift Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Swift Academy 课程共包含 2 节课。
诊断工具箱
使用简单的日志记录来查看状态;使用断言、前置条件和fatalError强制执行假设。
- 断言:仅在调试模式下检查
- 前置条件:发布版本中也会检查
- fatalError:立即停止
轻量级日志记录
打印更易读;debugPrint会显示更多细节(调试时很有用)。
let user = ["name": "Ana", "role": "admin"]
print("User:", user) // user-friendly
debugPrint("User:", user) // includes type details when available
let point = (x: 3, y: 5)
print("Point:", point)
debugPrint("Point:", point)断言(仅调试)
当条件为 false 时,断言会在调试模式下停止程序;在经过优化的发布构建中会被移除。
// Even numbers only (demo)
func half(of x: Int) -> Int {
assert(x % 2 == 0, "Expected even number, got \(x)")
return x / 2
}
print(half(of: 8)) // OK in Debug/Release
// In Debug, failing the assert would stop and print the message.
// In Release, assert checks are disabled by default.前置条件(发布版本中检查)
前置条件会在调试和发布模式下验证关键要求。对于绝不能发生的程序员错误,请使用它。
// Safe divide with required precondition
func safeDivide(_ a: Int, by b: Int) -> Int {
precondition(b != 0, "Divider must be nonzero")
return a / b
}
print(safeDivide(10, by: 2)) // 5
// If called with 0, precondition fails in Debug and Release.fatalError(立即停止)
fatalError会立即停止执行并报告消息。在开发期间,对于不可达的代码路径或尚未实现的功能,请使用它。
enum FileKind { case text, binary }
func open(kind: FileKind) {
switch kind {
case .text:
print("Open text mode")
case .binary:
print("Open binary mode")
// If we ever add a new case and forget to handle it, we could use:
// default: fatalError("Unsupported file kind")
}
}
open(kind: .text)何时使用哪一种
指南:
- 使用打印/debugPrint记录快速日志(之后移除,或改为由标志控制)。
- 使用断言执行仅限调试的开发者检查。
- 当要求失败时,如果程序在任何构建中都不能继续运行,请使用前置条件。
- 对于不可达或尚未实现的路径,请使用fatalError。
发布版本中检查的诊断项
快速检查:哪种诊断项在发布构建中仍会检查?
回顾
回顾:使用打印/debugPrint记录日志,使用断言(调试模式)和前置条件(发布模式也会检查)保护不变量,并使用fatalError处理真正不可达的状态。
常见问题解答
「日志记录、assert/precondition/fatalError」课时是免费的吗?
是的 — 「日志记录、assert/precondition/fatalError」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Swift Academy 课程的其余内容,请升级到 CoddyKit PRO。 Swift Academy 课程共包含 2 节课。
「日志记录、assert/precondition/fatalError」这节课中我会学到什么?
使用 print/debugPrint 记录状态,并根据不变量选择 assert (仅调试模式)、 precondition (发布版本也会检查)或 fatalError (导致崩溃)。 你通过在浏览器中直接运行的动手代码来练习 Swift Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Swift Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Swift Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 2 节。
「日志记录、assert/precondition/fatalError」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Swift Academy 课中编写并运行代码吗?
能。每节 Swift Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- XCTest 基础(目标、测试夹具)
- 日志记录、assert/precondition/fatalError