Swift中用户定义的choiceStepFunction()中的两个箭头的目的是什么? [英] What is the purpose of the two arrows in the user defined chooseStepFunction() in Swift?

查看:111
本文介绍了Swift中用户定义的choiceStepFunction()中的两个箭头的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里最后一个函数的返回类型中,双箭头表示什么?

What do the double arrows indicate in the return type of the last function here?

它们曾经用来表示两个不同的返回值吗?

Are they used to indicate two different return values?

如果是这样,并且chooseStepFunction()中的函数是不同类型的,您如何知道箭头的顺序?例如,如果stepForward()返回String

If so, how do you know which order the arrows are in, if the functions in chooseStepFunction() were different types? E.g., if stepForward() returned a String

func stepForward(input: Int) -> Int{
    return input + 1
}

func stepBackward(input: Int) -> Int{
    return input - 1
}

func chooseStepFunction(backwards: Bool) -> (Int) -> Int{
    return backwards ? stepBackward: stepForward
}

推荐答案

给出:

(x) -> (y) -> z

您将其读为:

接受x并返回接受y并返回z的函数.

A function which accepts x and returns a function which accepts y and returns z.

因此,在这种情况下,chooseStepFunction是一个接受bool并返回接受int并返回int的函数的函数.这是右关联的,因此您将其读取为:

So in this case, chooseStepFunction is a function that takes a bool and returns a function that takes an int and returns an int. This is right-associative, so you would read it as:

(backwards: Bool) -> ((Int) -> Int)

如果您记得第一组括号(在Bool附近)不是特别特殊,则最容易阅读.它们就像第二组(在Int附近). (实际上并不需要括号.(Int) -> IntInt -> Int相同.)

It's easiest to read this if you remember that the first set of parentheses (around Bool) aren't particularly special. They're just like the second set (around Int). (The parentheses aren't actually needed. (Int) -> Int is the same as Int -> Int.)

认识到这一点将对您有帮助:

Realizing this will help when you encounter currying:

func addTwoNumbers(a: Int)(b: Int) -> Int

这实际上与以下内容相同:

This is really the same as:

(a: Int) -> (b: Int) -> Int

接受int并返回int的函数.

A function that takes an int and returns a function that takes an int and returns an int.

这篇关于Swift中用户定义的choiceStepFunction()中的两个箭头的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆