Good Evening, Hi guys i am new with swift, so i try to make a simple calculator by converting an infix notation to a postfix notation. Basically the code gonna works like this, All numbers are pushed to the output when they are read. At the end of reading the expression, pop all operators off the stack and onto the output.
So i try to compile the code and it says that Fatal error: Unexpectedly found nil while unwrapping an Optional value:
can someone help with with this thank you so much :)
Fatal error: Unexpectedly found nil while unwrapping an Optional value:
import UIKit
var tokens: [String] = ["4 + 4 + 2"]
func precedence(op: String) -> Int{
if(op == "+" || op == "-"){
return 1
}
if(op == "*" || op == "/" || op == "%"){
return 2
}
return 0
}
func applyOp(a: Int, b: Int, op: String) -> Int{
switch op{
case "+":
return a + b
case "-":
return a - b
case "*":
return a * b
case "/":
return a / b
case "%":
return a % b
default:
return 0
}
return 0
}
func evaluate(tokens: [String]) -> Int{
var i: Int! = 0
var values: [Int] = []
var ops : [String] = []
while i < tokens.count{
if(tokens[i] >= "0" && tokens[i] <= "9"){
var val : Int = 0
while i < tokens.count && tokens[i] >= "0" && tokens[i] <= "9"{
val = (val * 10) + Int(tokens[i])!
i = i + 1
}
values.append(val)
i = i - 1
}
else{
while ops.count != 0 && precedence(op: ops[-1]) >= precedence(op: tokens[i]){
let val2 : Int! = values.popLast()
let val1 : Int! = values.popLast()
let op : String! = ops.popLast()
values.append(applyOp(a: val1, b: val2, op: op))
}
}
i = i + 1
}
while ops.count != 0{
let val2 : Int! = values.popLast()
let val1 : Int! = values.popLast()
let op : String! = ops.popLast()
values.append(applyOp(a: val1, b: val2, op: op))
}
return Int(values[-1])
}
print(evaluate(tokens: tokens))