user2661518 user2661518 - 3 months ago 15
Swift Question

try catch variable in swift

I am trying to add try catch against variable. Without try catch I this error:


fatal error: unexpectedly found nil while unwrapping an Optional value for variable Double(label.text!)!


So I want to catch above error. I tried below

do{
let value = try Double(label.text!)!
print("value\(value)")
} catch{
print("hi")
}


But it still gives same error and I also see this warnings:


No calls to throwing functions occur within try and catch block in unreachable...


Is this right way of using try catch block in swift?

edit: (not duplicate) If I just return
return Double(labelDisplay.text)
I get compilation error
value of option type String? not unwrapped, so I have to use
return Double(labelDisplay.text!)!` which is where if fails. That's why I was trying to catch it.

another edit: label is
@IBOutlet weak private var label: UILabel!


edit: return code

var displayValue: Double{
get{
print(labelDisplay.text.dynamicType)
return Double(labelDisplay.text!)!
}
set{
labelDisplay.text! = String(newValue)
}
}

Answer

I personally would use an if let, which I believe is what you are essentially trying to do.

if let value = Double(label.text!)!{
    print("value\(value)")
}else{
    print("hi")
}

Please let me know if this fits what you are trying to do, and if not, I'll be happy to help in any other way!

UPDATE:

if let value = Double(label.text!){
        print("value\(value)")
    }else{
        print("hi")
    }

This is the correct way. Note: The label text is only unwrapped, not the whole double. If the label.text! is a valid number ("3.14159") and not text like ("hello"), then the value will be printed. If not, the else statement will catch it.

UPDATE 2:

WORKING:

Declaration:

var displayValue: Double{
    get{
        return Double(label.text!)!
    }
    set{
        displayLabel.text! = String(newValue)
    }
}

Function:

if let value = Double(label.text!){
        print("value\(value)")

        displayLabel.text! = "\(displayValue)"

    }else{
        print("hi")
    }