Search code examples
swiftoption-typeunwrap

Unwrap variable which is not optional?


I came across these lines of code for a simple calculator app.

func processOperation (operation: Operation) {
    if currentOperation != Operation.Empty {
        if runningNumber != "" {
            rightValStr = runningNumber
            runningNumber = ""

            if currentOperation == Operation.Multiply {
                result = "\(Double(leftValStr)! * Double(rightValStr)!)"
            } else if currentOperation == Operation.Divide {
                result = "\(Double(leftValStr)! / Double(rightValStr)!)"
            } else if currentOperation == Operation.Subtract {
                result = "\(Double(leftValStr)! - Double(rightValStr)!)"
            } else if currentOperation == Operation.Add {
                result = "\(Double(leftValStr)! + Double(rightValStr)!)"
            }

leftValStr is declared as var leftValStr = ""

rightValStr is also declared as var rightValStr =""

I am wondering what the purpose of using "!" in \(Double(leftValStr)! / Double(rightValStr)!) is for? From what I know, "!" is for unwrapping optional. leftValStr and rightValStr here are not declared as Optional so why do we have to unwrap them?


Solution

  • Even if leftValStr and rightValStr are not optionals, you are force unwrapping Double(leftValStr) and Double(rightValStr) and the result of initializing Double with a String value can be nil.

    For example, you can't initialize a Double with a stackoverflow String.

    If you'd like to make sure that this conversion result is correct you can use an if let to avoid force unwrapping, for example:

    if let leftValDouble = Double(leftValStr) {
        // do your code
    } else {
        // handle error
    }
    

    Please remember that if you force unwrap a nil value, your code will crash.