Reputation: 6002
Is it possible to parse a closure as string at runtime in Swift? For example:
let y = 5
let myClosure = { (x: Double) -> Double in
return x * 2 + y
}
should give me "x * 2 + 5"
(for example a function call closureToString(myClosure)
). Is it possible to do something like this? Btw, I really mean at runtime because y
could be read from Command Line for example.
I don't think it's possible, just looking for confirmation^^ thank you ;)
Upvotes: 3
Views: 419
Reputation: 2471
// Im assuming y is a parameter along with x if not remove it .
// Im returning tuples to access both stringValue and DoubleValue
let myClosure = { (x: Double, y:Double) -> (DoubleValue: Double, StringValue:String) in
return (x * 2 + y,"\(x) * 2 + \(y)")
}
let MyClosureResult = myClosure(2,8)
// to accessString Value
MyClosureResult.StringValue
// to access DoubleValue
MyClosureResult.DoubleValue
Upvotes: 2
Reputation: 818
Why do you need it in a function? Couldn't you do something like this?
let y = 5
let myClosure = { (x: Double) -> Double in
println("x * 2 + \(y), x = \(x)")
return x * 2 + y
}
Upvotes: 2