如何在科特林的forEach之外返回?

时间:2018-07-30 03:10:03

标签: android kotlin

我希望返回aa@ logError("Done")之外的forEach行,但是return@aa不起作用,而break@label也不起作用。

还有,如果您使用return,它将返回有趣的lookForAlice

data class Person(val name: String, val age: Int)
val people = listOf(Person("Paul", 30), Person("Alice", 29), Person("Bob", 31))


fun lookForAlice(people: List<Person>) {
    people.forEach label@{
        logError("Each: "+it.name)
        if (it.name == "Alice") {
            logError("Find")                                 
            return@aa  //It's fault
        }
    }
    aa@ logError("Done")
}

lookForAlice(people)

2 个答案:

答案 0 :(得分:5)

对每个循环使用传统方式。

即改变

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = myCollection.dequeueReusableCell(withReuseIdentifier: "cellCollection", for: indexPath) as! CollectionViewCell
    cell.cellImage.image = UIImage(named: array[indexPath.item])

    if UIDevice.current.orientation.isLandscape{
        cell.cellImage.contentMode = .scaleAspectFill
    }
    else if UIDevice.current.orientation.isPortrait{
        cell.cellImage.contentMode = .scaleToFill
    }

    return cell
}

people.forEach label@{

并将for (it in people) { 更改为return


注意:在break

中阅读有关return的这些文章

`break` and `continue` in `forEach` in Kotlin

How do I do a "break" or "continue" when in a functional loop within Kotlin?(此问题可能是该问题的重复项)

答案 1 :(得分:0)

您想改用find。它将返回Person?。因此,您可以检查它是否为null。否则,您找到了Alice

data class Person(val name: String, val age: Int)
val people = listOf(Person("Paul", 30), Person("Alice", 29), Person("Bob", 31))
val alice: Person? = findAlice(people)


fun findAlice(people: List<Person>): Person? {
    return people.find { it.name == "Alice" }
}