-1

I am fetching data from database. Sometimes it occupies values and sometimes blank. so my app crashes while getting blank. I even used ! and ? to avoid crashing.

In cellForRowAtIndexPath method,

cell.profImg!.image = UIImage(named: (profArr.objectAtIndex(indexPath.row).valueForKey("avatar") as? String)!) 

App crashes while my profArr contains value

(

{

     avatar = ""

}

)

Is there any way to avoid crashing without checking variable length.

Bhavin Bhadani
  • 22,224
  • 10
  • 78
  • 108
Simran
  • 42
  • 7

1 Answers1

4
if let myValue = profArr.objectAtIndex(indexPath.row).valueForKey("avatar") as? String {
    // do something, value is not nil
} else {
    //do something else, value is nil
}

Edit

If you don't want to check, you can try something like this

var myImage = UIImage(named: ((profArr.objectAtIndex(row) as! NSDictionary).valueForKey("avatar") as! String?)!)
trusk
  • 1,634
  • 2
  • 18
  • 32
  • Thanks for reply Alex Bartiş. But is there any solution to handle crashing without conditions – Simran Sep 08 '15 at 07:54
  • afaik not, why are you not happy with this solution? – Glenn Sep 08 '15 at 08:00
  • @SimranJit , with Swift 2.0 new built-in error-catching capabilities were added. Check the "Swift 2.0 Update" in the first answer [here](http://stackoverflow.com/questions/24010569/error-handling-in-swift-language). – MustangXY Sep 08 '15 at 10:50