0

This is my code:

print("Please enter your formula:")

let formula = readLine()

if formula == ("[0-9+-*/%]"){
    let result = NSExpression(format: formula)
    let result1 = result.expressionValue(with: nil, context: nil) as? Int
    print("\(result1)")
} else {
    print("please type a real formula")
}

My code keeps saying my "format: formula" has problems.

Value of optional type 'String?' must be unwrapped to a value of type 'String'

rmaddy
  • 314,917
  • 42
  • 532
  • 579
tktkt
  • 1
  • Look at the reference documentation for `readLine` and note its return type. Then look at the documentation for `NSExpression init(format:)` and note the parameter's expected type. Note the difference. – rmaddy Apr 07 '19 at 17:45
  • You should also spend lots of time in the Swift book reading about [Optionals](https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html#ID330). It's very important to learn and understand optionals in Swift. – rmaddy Apr 07 '19 at 17:46
  • Note also that `if formula == ("[0-9+-*/%]")` does *not* do a regular expression match. – Martin R Apr 07 '19 at 18:02

0 Answers0