Learn Courses My Dashboard

Math calculation on string - swift

Hello! How we can compute strings in swift. For example, “5*4-1+3”

Like this:

let expression = NSExpression(format:"5*4-1+3")
let value = expression.expressionValue(with: nil, context: nil) as? Int

value returned will be an Optional Int

See much more that can be done with NSExpression here: NSExpression - NSHipster (though be warned that it’s several years old and some of the functions have since been renamed)