类型"Int - > Bool","Int-> Bool - > Int","Int-> String - > Int-> Bool"

bel*_*ian 5 ios swift

有一个功能:

 func (first: Int) -> Int -> Bool -> String {

    return  ?
 }
Run Code Online (Sandbox Code Playgroud)

如何写回报值?我对上面的func的返回类型非常困惑.

Cri*_*tik 9

解析函数/闭包返回时,从右到左阅读.右边最右边的是返回类型,你可以将其余的放在括号中.

因此,您的函数声明等同于

func (first: Int) -> ((Int) -> ((Bool) -> String))
Run Code Online (Sandbox Code Playgroud)

func (first: Int)(_ second: Int)(_ third: Bool) -> String
Run Code Online (Sandbox Code Playgroud)

虽然Swift 3.0不再支持这种形式(感谢@Andrea的提升).

这被称为函数currying.函数返回一个带有Intas参数的函数,并返回另一个带有Boolas参数并返回a的函数String.这样您就可以轻松地链接函数调用.

因此,方法体必须返回列表中的第一个函数,该函数具有以下签名:

func ((Int) -> ((Bool) -> String))
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样调用它:

f(1)(2)(true)
Run Code Online (Sandbox Code Playgroud)


Vin*_*zzz 2

假设你定义了一个闭包

let closure: Int -> Bool
Run Code Online (Sandbox Code Playgroud)

一旦知道了闭包类型(参数类型和返回类型),编写它就很容易了,您可以命名参数列表,然后是关键字,in然后是函数体(如果函数返回类型不是,则末尾有一个返回)它Void(又名()

// closure that returns if an integer is even
closure = { integer in 
    return integer %2 == 0
}
Run Code Online (Sandbox Code Playgroud)

在你的情况下,Int -> Int -> Bool -> String意味着

  • 以 Int 作为参数并返回的函数
    • 以 Int 作为参数并返回的函数
      • 以 Bool 作为参数并返回的函数
        • 一个字符串

在代码中编写的一种方法:

func prepareForSum(first: Int) -> Int -> Bool -> String {
    return  { secondInteger in
        return { shouldSumIntegers in

        var result: Int
        // for the sake of example
        // if boolean is true, we sum
        if shouldSumIntegers {
            result = first + secondInteger
        } else {
            // otherwise we take the max
            result = max(first, secondInteger)
        }

        return String(result)
    }
 }
Run Code Online (Sandbox Code Playgroud)

现在你可以像这样使用它

let sumSixteen = prepareForSum(16) // type of sumSixteen is Int -> Bool -> String

let result1 = sumSixteen(3)(true) // result1 == "19"
let result2 = sumSixteen(26)(false) // result2 == "26"
Run Code Online (Sandbox Code Playgroud)