【问题标题】:Why does function has multiple return types in swift?为什么函数在swift中有多种返回类型?
【发布时间】:2018-12-15 10:23:13
【问题描述】:

我注意到这个函数有一个独特的返回类型

func chooseStepFunction(backward: Bool) -> (Int) -> Int {
func stepForward(input: Int) -> Int { return input + 1 }
func stepBackward(input: Int) -> Int { return input - 1 }
return backward ? stepBackward : stepForward
}

【问题讨论】:

标签: swift


【解决方案1】:

这个函数实际上只是返回另一个函数,Int 作为参数和返回类型。这样做:

(Int) -> Int

在这种情况下,此函数返回您的子函数之一。


那么当你需要得到子函数的结果时,就这样做

chooseStepFunction(backward: true)(1)  /* returns 0 */
chooseStepFunction(backward: false)(1) /* returns 2 */

【讨论】:

  • 这叫处理程序吗?
  • @SubashChandru 我不确定是否诚实。它是另一个函数的参数和返回类型。
  • @SubashChandru 不。这只是一个返回函数的函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多