Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Closure to String

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 ;)

like image 263
borchero Avatar asked Aug 14 '26 17:08

borchero


2 Answers

// 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
like image 147
sriram hegde Avatar answered Aug 18 '26 15:08

sriram hegde


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
}
like image 41
Bell App Lab Avatar answered Aug 18 '26 15:08

Bell App Lab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!