lmiguelvargasf
lmiguelvargasf

Reputation: 69735

How can I return a function that depends on two functions?

I have the following function:

private func getFunctionToPlot() -> ((Double) -> Double) {
    var function: (Double) -> Double = sin + cos
    return function

}

I would like to return a function that takes a double and returns a double, but this functions should be something as sin + cos. Both sin and cos independently take a double and return a double, but how can I return something as sin($0) + cos($0).

Upvotes: 1

Views: 76

Answers (2)

matt
matt

Reputation: 534958

Your question is a little broad, but the line you claim doesn't compile does compile; there's nothing wrong with what you're doing. The only problem is that your code is incomplete. Here is a test example that is complete:

private func getFunctionToPlot() -> ((Double) -> Double) {
    var function: (Double) -> Double
    function = {_ in return 2.0}
    return function
}

EDIT As for your revised question, here's a test example of the sort of thing you now seem to be trying to do:

func sin(_ d:Double) -> Double {return 1}
func cos(_ d:Double) -> Double {return 1}
private func getFunctionToPlot() -> ((Double) -> Double) {
    let f1: (Double) -> Double = sin
    let f2: (Double) -> Double = cos
    return {f1(f2($0))} // or maybe f1($0) + f2($0)
}

Upvotes: 2

Abhra Dasgupta
Abhra Dasgupta

Reputation: 525

Just assign a closure to function and it will work. Current in your code snippet the function has value "nil" and since the return type is not "optional"(i.e., ((Double) -> Double)?) therefore the return type mismatches.

One possible way is either assign function a value:

private func getFunctionToPlot() -> ((Double) -> Double) {
    var function: (Double) -> Double
    function = { input in
        return input * 2
    }
    for element in brain.program {
        // do something
    }
    return function
}

Another approach will be make return type optional

private func getFunctionToPlot() -> ((Double) -> Double)? {
    var function: ((Double) -> Double)?
    for element in brain.program {
        // do something
    }
    return function
}

Upvotes: 2

Related Questions