I am new to SWIFT and now on the topic of couriers there is such a question, I understand their advantage and ease of use, but the question is that when, for example, you need to write 3 functions 3 different coolers, you can understand what they are doing only by understanding code ...

After all, we do not give any name to them ... As for me it is not very convenient, sit reading the entire courier to understand what he is doing.

Is there any way to call him?

Example

func filterArray(array: [Int], f: (Int) -> Bool) -> [Int] { var filtered = [Int]() for value in array { if f (value){ filtered.append(valeu) } } return filtered } filterArray(numbers) {$0 % 2 == 0} filterArray(numbers) {$0 % 2 == 1} 

In this case, I understand that this part of the code is called the {$0 % 2 == 0} clause and it differs from this {$0 % 2 == 1} , but this can only be understood by understanding what they are doing.

It seems to me that if, instead of a kloger, functions are defined, named and passed to a function, it will be clear that we are serving ... And it turns out that the courier is an anonymous function that can be understood only by reading it.

  • one
    can you give an example? - Max Mikheyenko 2:49 pm
  • @MaxMikheyenko Posted by - Aleksey Timoshchenko
  • By the way, there is quite often used word "short circuit". - VladD
  • @VladD By the way there are a lot of frequently used words in everyday speech. It probably all depends on the person and his field of activity ... banter)) - Aleksey Timoshchenko

2 answers 2

For this, it is also a closet to perform simple or obvious functions. Otherwise, it is better to use functions with values ​​and comment parts of the code :)

    In Swift, both a function and a closure can be assigned to a variable.

    Here is an example:

     var closure:(Int)->Bool = { number in return number % 2 == 0 } func isIntegerEven(integer: Int, closure:(Int)->Bool) { if closure(integer) { print("Число четное") } else { print("Число не четное") } } isIntegerEven(integer: 3, closure: closure) 

    Create a closure variable and set its closure as a value. Next, we create the isIntegerEven function, into which we pass the number and the closure. In the body of the function, a closure is called to which the number is transmitted for checking whether it is even or not. Next, the function is called with parameters.

    So you can call closures. In your example:

     func filterArray(array: [Int], f: (Int) -> Bool) -> [Int] 

    the closure name is f .