【发布时间】:2017-12-10 12:38:35
【问题描述】:
我在处理非抛出函数(如重写方法、委托方法或数据源方法)中的错误时遇到问题。我只是想出了记录错误,你知道这不是一个好的错误处理策略。还有其他方法,方法等吗?谢谢。
编辑:
enum SomethingError : Error{
case somethingFailed
}
var anObject : AnObject?
........
........
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell throws{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
guard let anObject = anObject else{
throw SomethingError.somethingFailed
//and maybe return unprocessed cell but you cannot return anything after "throw", or you cannot "throw" after "return"
}
.....
.....
return cell
}
你不能这样做,因为 :collectionView:cellForItemAt:indexPath 不是一个抛出函数,它必须返回一个单元格。我怎样才能在这里发现错误?这就是问题。仅通过日志记录?
编辑:我知道我可以使用if let 但我想接住/扔掉;在此处处理错误。
【问题讨论】:
-
一个具体的例子会很有帮助。
-
定义“错误”,因为它没有抛出错误?你有方法的例子吗?
-
你不能
throwcellForItem出现错误,但你可以catch抛出错误。基本上避免委托和数据源方法中的任何可以退出范围的代码。
标签: swift error-handling