ios - 快速条件函数返回

标签 ios function swift return conditional

我想知道如何快速管理有条件的返回。例如,我根据调用的 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/

相关文章:

ios - 核心数据 NSFetchedResultsController 和批量大小设置加载所有行

ios - iOS:使用Spotify SDK在后台继续播放音乐

postgresql - 是否可以在 postgresql 中使用 for 循环(功能)

javascript - 关于给定负数将函数返回为 'undefined' 的问题?

ios - 插入新行后如何停止 UITableView 滚动到顶部?

ios - 如何在原型(prototype)单元格中使用 UIImageView 在 UITableView 中创建视差效果

ios - 将图像数组保存为 PFFiles

ios - 如何解析和访问 HTTPresponse 中的特定数据

php - 从使用的角度来看,私有(private)函数和保护类函数有什么区别?

ios - 如何在 Xcode 中为大量现有的 swift 文件和类添加前缀