Skip to content

Instantly share code, notes, and snippets.

@josephchang10
Created December 16, 2016 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josephchang10/87491e531e0300ad96077ce8ad32c446 to your computer and use it in GitHub Desktop.
Save josephchang10/87491e531e0300ad96077ce8ad32c446 to your computer and use it in GitHub Desktop.
Guard
func objectAtIndexPath(indexPath: NSIndexPath) -> Object {
guard let result = fetchedResultsController.objectAtIndexPath(indexPath)
as? Object else
{
fatalError("Unexpected object at \(indexPath)")
}
return result
}
@josephchang10
Copy link
Author

很多时候我们用 Swift 的 guard 关键字来更好地表达哪些地方出错了。例如 fetched results controller 返回的类型是 NSManagedObject 的对象,我们知道它必须是一个特定的子类,我们使用 guard 来保证向下转换,并在出错的时候使用 fatal error 来终止程序。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment