Bool & # 8594; Int", "Int-> String & # 8594; Int-> Bool" There is a func function: func (first: Int) -> Int -> ...">

Type "Int & # 8594; Bool", "Int-> Bool & # 8594; Int", "Int-> String & # 8594; Int-> Bool"

There is a func function:

func (first: Int) -> Int -> Bool -> String { return ? } 

How to write the return value? I'm so confused by the inverse type as the func function above.

+5
source share
2 answers

let's say you define a closure

 let closure: Int -> Bool 

as soon as the closure type is known (parameter type and return type), writing it is quite simple, you name the parameter list, followed by the in keyword, and then the body of the function (with a return at the end if the function return type is not Void (aka () )

 // closure that returns if an integer is even closure = { integer in return integer %2 == 0 } 

In your case, Int -> Int -> Bool -> String means

  • a function that takes an Int parameter as a parameter and returns
    • a function that takes an Int parameter as a parameter and returns
      • a function that takes a bool as a parameter and returns
        • a String

Code entry method:

 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) } } 

now you can use it like that

 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" 
+2
source

Reading from right to left when it comes to the parsing / closing function. The correct appearance is the type of the return value, and you can put it in parentheses.

So your function declaration is equivalent

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

and

 func (first: Int)(_ second: Int)(_ third: Bool) -> String 

although this form will no longer be supported in Swift 3.0 (thanks @Andrea for heads).

This is called the currying function . The function returns a function that takes an Int argument as an argument and returns another function that takes a Bool as parameter and returns String . This way you can easily call functions.

So, the body of your method should return the first function in the list, which has the following signature:

 func ((Int) -> ((Bool) -> String)) 

Then you can call it like this:

 f(1)(2)(true) 
+9
source

Source: https://habr.com/ru/post/1239396/


All Articles