macOS 文档处理与用户界面搭建
1. 错误处理与 guard 关键字
在开发文档加载和保存系统时,会用到 err 方法,示例如下:
// Load the text data as RTF
guard let documentText = NSAttributedString(rtf: documentTextData,
documentAttributes: nil) else {
throw err(.cannotLoadText)
}
这里使用了 guard 关键字, guard 关键字是在 Swift 2 中引入的,它能帮助我们避免编写两种令人头疼的代码:“if 金字塔”(有时也称为“厄运金字塔”)和提前返回。
“if 金字塔”示例:
if let someObjectA = optionalA {
if let someObjectB = optionalB {
if let someObjectC = optionalC {
// Do something that relies on all three of these optionals
// having a value
}
}
}
提前返回示例:
超级会员免费看
订阅专栏 解锁全文
1216

被折叠的 条评论
为什么被折叠?



