-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
  • 78,605
  • 19
  • 187
  • 280
sirvon
  • 2,547
  • 1
  • 31
  • 55
  • 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

2 Answers2

2

Try this:

for aps in apResults where aps != nil {
    // do your things
}
Code Different
  • 90,614
  • 16
  • 144
  • 163
0

This should do what you need:

for case let aps? in apResults {
    // use aps which is ".some" value
}