Reputation: 159
I am doing a coding project. In this coding project I am constructing a calculator. I wanted to use natural log (ln). But keep getting an error that says Anonymous closure argument not contained in a closure
. Here is my code, it is in a struct file:
import Foundation
struct CalculatorBrain{
private var accumulator: Double?
private enum Operation{
case unaryOperation((Double) -> Double)
}
private var operations: Dictionary<String,Operation> =
[
// Unary Operations
"ln" : Operation.unaryOperation(log( $0 )), // this is the line where the error is
"√" : Operation.unaryOperation(sqrt),
"cos" : Operation.unaryOperation(cos),
"sin" : Operation.unaryOperation(sin),
"tan" : Operation.unaryOperation(tan),
"sinh" : Operation.unaryOperation(sinh),
"cosh" : Operation.unaryOperation(cosh),
"tanh" : Operation.unaryOperation(tanh),
"%" : Operation.unaryOperation({ $0 / 100 }),
"±" : Operation.unaryOperation({ -$0 }),
]
mutating func performOperation(_ symbol: String){
if let operation = operations[symbol]{
switch operation {
case .unaryOperation (let function):
if accumulator != nil{
accumulator = function(accumulator!)
}
Upvotes: 0
Views: 2598
Reputation: 53010
Consider your code, for square root and trig functions you wrote, for example:
"cos" : Operation.unaryOperation(cos)
which just references the function, here cos
, by name resulting in a function value. For two others you wrote a closure, for example:
"%" : Operation.unaryOperation({ $0 / 100 })
here you have use a closure ({ ... }
) to obtain your function value. Then there is your log
line producing an error:
"ln" : Operation.unaryOperation(log( $0 ))
this is neither the first or second case. Did you intend to write a closure, i.e. { log($0) }
, or just reference the existing function, i.e. log
? Either is valid.
Pick one of the above two options, then get some sleep/coffee ;-)
HTH
Upvotes: 2
Reputation: 93191
You should not write $0
because there is no closure, just specifying the name of the function is enough:
"ln" : Operation.unaryOperation(log)
Upvotes: 2