快速条件函数返回

Sup*_*ete 5 return function conditional-statements ios swift

我想知道如何快速管理有条件回报。例如,我返回一个自定义 UICollectionViewCell,具体取决于调用哪个 collectionview 委托:

    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
      }
}
Run Code Online (Sandbox Code Playgroud)

编译器说“函数中缺少 return 语句期望返回 UICollectionViewCell”,即使在这两种情况下我都返回一个单元格。

我解决了它添加

return UICollectionViewCell()
Run Code Online (Sandbox Code Playgroud)

在函数的底部,但我认为这不是正确的方法。

我知道我可以在第一个“if”上方声明单元格,修改它并在“if”之外的函数末尾返回它,但随后“dequeueReusableCellWithIdentifier”调用会挂起。

谢谢你们。

erd*_*ser 6

为了解释 @MidhunMP 的答案,现在您的代码可以在没有任何返回值的情况下结束。例如,看看这段代码,它与您的代码类似:

func myFunc() -> Int {
    let myNumber = random() % 3
    if myNumber == 0 {
        return 0
    }
    else if myNumber == 1 {
        return 1
    }
}
Run Code Online (Sandbox Code Playgroud)

如果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
}
Run Code Online (Sandbox Code Playgroud)

或者,

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,使用第一个,因为它更优雅并且更容易理解其含义。