func postFix(_ expr: String) -> Int {
// write your code here
let nums = expr.components(separatedBy:CharacterSet.decimalDigits.inverted)
.joined()
let set = CharacterSet(charactersIn: "+*/%-")
var ch = expr.components(separatedBy: set.inverted).joined()
ch.append(" ")
var rslt = String()
for i in 0..<nums.count {
let index = str.index(str.startIndex, offsetBy: i)
rslt.append(nums[index])
rslt.append(ch[index])
}
let theSet = CharacterSet(charactersIn: "+*/%-0123456789")
let final = rslt.components(separatedBy: theSet.inverted).joined()
let expn = NSExpression(format: final)
let chal = expn.expressionValue(with: nil, context: nil)
return chal as! Int
}
print(postFix("4 1 - 2 *"))
Im making a method to resolve a math operation from an unsorted string the only problem I'm facing is I couldn't determine operating from left-associative . instead of 4 - (1 * 2) = 2 I want it to start from left side and ignore whether to start with * or / first so (4 - 1 ) * 2 = 6