我希望返回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)
答案 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" }
}