本文介绍了Swift-从闭包退出外部函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Kotlin中,您可以从闭包中的外部函数返回.

In Kotlin, you can return from an outer function from a closure.

   fun main(args: Array<String>) {
     val letters = listOf("A", "B", "C")

     fun lookForLetter(letter: String, letters: List<String>){
        letters.forEach { l ->
          if (l == letter) {
            println("Found")
            return
          }
          println(l)
        }
        println("Completed")
      }

      lookForLetter("A", letters = letters)
   }

输出:

找到

在Swift中,return退出闭包的执行

In Swift, return exits execution of the closure

var letters = ["A", "B", "C"]

func lookForLetter(letter: String, letters: [String]) {
    letters.forEach { (l) in
        if l == letter {
            print("Found");
            return
        }
        print(l)
    }
    print("Completed")
}

lookForLetter(letter: "A", letters: letters)

输出:

找到

B

C

已完成

有没有办法在Swift中获得相同的结果?

Is there a way to achieve the same result in Swift?

推荐答案

Swift没有来自闭包的非本地返回.换句话说,没有直接的方法可以退出多个级别.这仅适用于Kotlin中的内联函数,但是Swift没有这种区别.

Swift does not have non-local returns from closures. In other words, there is no direct way to return out of multiple levels. This only works with inlined functions in Kotlin, but Swift does not have this distinction.

还有其他收集方法会在找到元素后停止,例如index(where:).

There are other collection methods which stop once an element is found, for example index(where:).

func lookForLetter(letter: String, letters: [String]) {
    guard let _ = letters.index(where: { (l) in
        if l == letter {
            print("Found");
            return true
        }
        print(l)
        return false
    }) else {
        print("Completed")
        return
    }
}

这篇关于Swift-从闭包退出外部函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 23:31