我想知道如何快速管理有条件的返回。例如,我根据调用的 collectionview 委托(delegate)返回一个自定义 UICollectionViewCell:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if (collectionView.isEqual(collectionView1)) {
var cell = self.epgCollectionView.dequeueReusableCellWithReuseIdentifier("Cell1", forIndexPath: indexPath) as Cell1
return cell
}
else if (collectionView.isEqual(collectionView2)) {
var cell = self.epgCollectionView.dequeueReusableCellWithReuseIdentifier("Cell2", forIndexPath: indexPath) as Cell2
return cell
}
}
编译器说“在返回 UICollectionViewCell 的函数中缺少返回语句”,即使在这两种情况下我都返回一个单元格。
我添加解决了
return UICollectionViewCell()
在函数的底部,但我认为这不是正确的方法。
我知道我可以在第一个“if”之上声明单元格,修改它并在“if”之外的函数末尾返回它,但随后“dequeueReusableCellWithIdentifier”调用挂起。
谢谢大家
最佳答案
为了解释@MidhunMP 的回答,现在您的代码可以在没有任何返回值的情况下结束。例如,看看这段代码,它与您的相似:
func myFunc() -> Int {
let myNumber = random() % 3
if myNumber == 0 {
return 0
}
else if myNumber == 1 {
return 1
}
}
如果 myNumber
是 2 怎么办?函数结束时没有任何返回值,这是不可能发生的。
要么将 return 语句移到代码末尾,要么添加一个 else
子句。两者都确保您的函数在任何情况下都会返回一个值。
您将需要:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell = UICollectionViewCell()
if (collectionView.isEqual(collectionView1)){
cell = self.epgCollectionView.dequeueReusableCellWithReuseIdentifier("Cell1", forIndexPath: indexPath) as Cell1
} else if (collectionView.isEqual(collectionView2)){
cell = self.epgCollectionView.dequeueReusableCellWithReuseIdentifier("Cell2", forIndexPath: indexPath) as Cell2
}
return cell
}
或者,
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell = UICollectionViewCell()
if (collectionView.isEqual(collectionView1)){
cell = self.epgCollectionView.dequeueReusableCellWithReuseIdentifier("Cell1", forIndexPath: indexPath) as Cell1
return cell
} else if (collectionView.isEqual(collectionView2)){
cell = self.epgCollectionView.dequeueReusableCellWithReuseIdentifier("Cell2", forIndexPath: indexPath) as Cell2
return cell
} else {
return cell;
}
}
但是,使用第一个,因为它更优雅,更容易理解其含义。
关于ios - 快速条件函数返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27861387/