Daniele C Daniele C - 6 months ago 15
Swift Question

Single-line function in Swift

Can someone explain me how to write this function, which should return the

factorial
of x.

The way I tried to do it gives me an
error
.

This line is inside a dictionary and refers to
Operation.UnaryOperation
that is
(Double) -> Double


I tried to write the function I need extensively, It should look like this:

private func factorial(n: Double) -> Double {
if (n<=1) {
return 1
}
return n * factorial(n-1)
}


Now I need to convert it to a single-line function, how do I do it? would it look something like this?, why am I getting an error?

"x!" : Operation.UnaryOperation({if ($0<=1) {return 1} else {return $0 * factorial($0-1)}}),

Answer

Just embed the named function in the closure - like this

enum Operation {
    case UnaryOperation( (Double) -> Double)
    case BinaryOperation( (Double, Double) -> Double)
}

let dictionary: [String: Operation] = [
    "+" : Operation.BinaryOperation({ return $0 + $1 }),
    "!" : Operation.UnaryOperation({
        arg in
        func factorial(x: Double) -> Double {
            if x <= 1 {
                return 1
            } else {
                return x * factorial(x - 1)
            }
        }
        return factorial(arg)
    })
]
Comments