使用do-catch抛出错误
do {
existingPiggyBanks = try context.fetch(fetchRequest)
} catch {
throw CreateError.fetchFaild(error)
}
enum CreateError {
case fetchFaild(Error)
}
Xcode提示定义的枚举 CreateError 存在错误:
Thrown expression type 'CreateStepViewModel.CreateError' does not conform to 'Error'
该报错表示抛出的 CreateStepViewModel.CreateError 不符合 Error 规范,因此无法抛出错误。
enum CreateError: Error {
case fetchFaild(Error)
}
解决方案:CreateError 需要遵守Error协议,才可以抛出Error类型的错误。
注意:当抛出 Error 时,方法也声明 throws 关键词,才能处理抛出的 Error 类型错误。
