Home>

An error occurs when you unwrap. What should I do?

@ IBOutlet weak var str: UILabel!
func doubleNum ()
    {
        // Value of optional type 'String?' Must be unwrapped to a value of type 'String'
        var db: Double = NSString (string: str.text) .doubleValue
    }
  • Answer # 1

    By the way, to make String a Double

    let a_String = "1234.98"
    let a_Double = Double (a)

    is enough.

  • Answer # 2

    Unwrap usingif let,guard let,??or whatever is appropriate.

    Example:

    if let db = NSString (string: str.text) .doubleValue {
        // If the string can be converted to Double type
    } else {
        // If conversion failed
    }