0

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 usereturn 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)
    }
}
user2661518
  • 2,677
  • 9
  • 42
  • 79
  • 2
    Possible duplicate of [swift can catch fatal error?](http://stackoverflow.com/questions/31335023/swift-can-catch-fatal-error) – Hamish Aug 31 '16 at 16:45
  • 1
    Also possible duplicate of [swift force-unwrapping exception not propagated](http://stackoverflow.com/questions/34628999/swift-force-unwrapping-exception-not-propagated) – Hamish Aug 31 '16 at 16:49
  • Can you give the code where you are trying to return it. – Dravidian Aug 31 '16 at 17:46
  • @Dravidian updated – user2661518 Aug 31 '16 at 17:57
  • First of all, there is no error that is thrown in the block when you typecast `labelDisplay.text!`. so no use trying `try-catch` also what is it exaclty that you want.. – Dravidian Aug 31 '16 at 18:04
  • @Dravidian If I click on say button '5' it works fine, but if I click on button say 'a' it gives error. If I jus return `return Double(labelDisplay.text!)` I get compilation error `value of option type Double? not unwrapped...` – user2661518 Aug 31 '16 at 18:30

3 Answers3

2

making double from string does not throw so you will not catch anything, you should

if let value = Double(label.text) {
    //here it worked out 
    print("value \(value)")
} else {
    //it failed
}
Lu_
  • 2,577
  • 16
  • 24
  • I am trying to return variable `return Double(labelDisplay.text!)!` when it fails, If I just return `return Double(labelDisplay.text!)`. I get compilation error `value of option type String? not unwrapped...` – user2661518 Aug 31 '16 at 16:58
  • label is @IBOutlet weak private var label: UILabel! – user2661518 Aug 31 '16 at 17:10
1

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")
    }
Jake Braden
  • 489
  • 5
  • 15
  • I am trying to return `return Double(labelDisplay.text!)!` when it fails, If I just return `return Double(labelDisplay.text!)`. I get error `value of option type String? not unwrapped...` – user2661518 Aug 31 '16 at 16:58
  • also if I return `return Double(labelDisplay.text)` I get compilation error `value of option type....` so can't use if statement as above – user2661518 Aug 31 '16 at 17:00
  • label is @IBOutlet weak private var label: UILabel! – user2661518 Aug 31 '16 at 17:10
  • I updated and tested my answer, everything seems to be working perfectly now! – Jake Braden Aug 31 '16 at 17:43
  • Change `return Double(labelDisplay.text!)!` to `return Double(labelDisplay.text!)` – Jake Braden Aug 31 '16 at 18:04
  • If I click on say button '5' it works fine, but if I click on button say 'a' it gives error. If I just return `return Double(labelDisplay.text!)` I get compilation error `value of option type Double? not unwrapped...` – user2661518 Aug 31 '16 at 18:30
  • Unwrap the value `labelDisplay.text! = String(newValue!)` – Jake Braden Aug 31 '16 at 19:15
  • It's failing at `return Double(labelDisplay.text!)!` not `newValue` – user2661518 Aug 31 '16 at 19:48
  • I've added new code, tested it, and it's running perfectly in my compiler. If the label is somehing like 'A', it prints "Hi", and if it is a number, it sets the displayLabel to the number. – Jake Braden Aug 31 '16 at 20:09
1

Actually, it does exist a try-catch operation in Swift. In the official documentation at Apple's Website, explains that this should be done like:

do {
    try expression
    statements
} catch pattern 1 {
    statements
} catch pattern 2 where condition {
    statements
}

For example:

var vendingMachine = VendingMachine()
vendingMachine.coinsDeposited = 8
do {
    try buyFavoriteSnack("Alice", vendingMachine: vendingMachine)
} catch VendingMachineError.InvalidSelection {
    print("Invalid Selection.")
} catch VendingMachineError.OutOfStock {
    print("Out of Stock.")
} catch VendingMachineError.InsufficientFunds(let coinsNeeded) {
    print("Insufficient funds. Please insert an additional \(coinsNeeded) coins.")
}

The source of this can be found here: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html

J Manuel
  • 3,010
  • 22
  • 39