-1

I've been getting this error...

[2017-02-27 15:11:23] NONE us us_crdrscrdrsge NONE [2017-02-27 15:11:23] brea crdrs crdrs_ar united states [2017-02-27 15:11:23] brea crdrs crdrs_daz1 united states [2017-02-27 15:11:23] brea crdrs crdrs_dev united states [2017-02-27 15:11:23] brea crdrs crdrs_devgen united states [2017-02-27 15:11:24] NONE us us_ctabscaninv NONE [2017-02-27 15:11:24] NONE us us_ctabscanstmt NONE fatal error: unexpectedly found nil while unwrapping an Optional value 2017-02-27 15:11:24.111276 Mobile[647:47234] fatal error: unexpectedly found nil while unwrapping an Optional value

How can I protect against nil values in this for loop:

```

  let apResults = realm.objects(DestinationNoEnum.self).
           filter("destinationRegionCode = 'ap'")


  for aps in apResults {
        autoreleasepool {
        print("\(aps.destinationCity) \(aps.destinationCode) 
         \(aps.destinationName) \(aps.destinationCountry)")
        }}

the apResults array is created via a realm query. There's like 1000 entries in the db.

Hamish
  • 74,809
  • 18
  • 177
  • 265
sirvon
  • 2,453
  • 1
  • 30
  • 51
  • This http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu looks like it has two good answers. Either explicitly check if aps != nil , or use their example for optional biding – Gonen I Feb 27 '17 at 23:58
  • Can you share the code for your `aps` entity? I don't think you should get back nil elements when iterating `apResults`. – Dave Weston Feb 28 '17 at 00:29
  • Are you using implicitly unwrapped optionals, anywhere? – Alexander Feb 28 '17 at 00:31

1 Answers1

2

Try this:

for aps in apResults where aps != nil {
    // do your things
}
Code Different
  • 82,550
  • 14
  • 135
  • 153