Is a function declaration to return something also empty?

Is there any way to declare such a function that I don't need to return a value? For example, I have an Array extension:

extension Array {
    func forEach(function: (element: T) -> ()) {
        for e in self {
            function(element: e)
        }
    }
}

Now I want:

textFields.forEach{$0.resignFirstResponder()}

And I can not, because the function is declared to return Void.

This will fix this:

textFields.forEach{$0.resignFirstResponder();return}

But is there a general way to declare such a function so that I can return any value or Void?

Thank!

+4
source share
2 answers

If you add a second general parameter without restrictions and enter a function to return it, then any return value will be accepted:

extension Array {
    func forEach<U>(function: (Element) -> U) {
        for e in self {
            function(e)
        }
    }
}

func f(i: Int)->Int {
    return i * 2
}

func g(i: Int) -> Double {
    return Double(0.0)
}

func h(i: Int) {
    println("\(i)")
}

let a = [1,2,3]
a.forEach(g)  // U will be an Int
a.forEach(f)  // U will be a Double
a.forEach(h)  // U will be a ()

However, Id strongly recommends you not to do this and use it instead for…in.

, . ( ), for…in , , .

, . , :

// function that does something side-effecty, but
// if it achieves some goal, exist early
func someFunc(a: [Int]) {
    a.forEach { i -> () in
        // goal achieved early,
        // return from func
        return
    }
    assert(false)
}

- , - ( ). forEach . , , , forEach, ( , continue ).

+3

map():

let textFields : [UITextField] = [] // or whatever
textFields.map{$0.resignFirstResponder()}

, , map forEach.

0

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


All Articles