-4

I have a code to sort array of object MyDate, which since is Any, and the value is set from ObjectMapper, the value of since get from json like this:

... 
"since": "1536642141",
... 

Those code run well in Xcode 9.4.1 but got crash in Xcode 10.

tempDates = tempDates.sorted(by: { Int(String.init(describing: $0.since))! < Int(String.init(describing: $1.since))!  })

The crash message is "Fatal error: Unexpectedly found nil while unwrapping an Optional value" Is this a bug of Xcode? How could I fix it?

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
cat
  • 357
  • 1
  • 5
  • 14
  • Why is `since` type `Any`? Why not make it a `String`? – Ashley Mills Oct 01 '18 at 11:04
  • It strongly depends on other parts of your code, when you get some runtime error on a line. Please try to show all relevant code, simplified but enough to reproduce your issue, is preferred. – OOPer Oct 01 '18 at 11:11
  • 1
    @AshleyMills it should be Int or Double, it's a timestamp (September 11, 2018 5:02:21 AM) – ielyamani Oct 01 '18 at 11:16
  • Yes, that's true - seems like their webservice needs work though as it's returning a string! – Ashley Mills Oct 01 '18 at 11:21
  • I can't set since to String, because sometimes it return Int, in some other case it is "since": 1536642141 – cat Oct 02 '18 at 01:36

1 Answers1

-1

There can be three reasons for Int to return nil when initialized with a random string.

  1. When string has digits greater than 32-bit/64-bit length
    let a = Int(String.init(describing: "153664214187878888878878"))

  2. When string does not contain any digits
    let a = Int(String.init(describing: "heyyowhynodigits"))

  3. When string has other characters with digits
    let a = Int(String.init(describing: "heyyowhynodigits"))

These reasons should be valid for both XCode 9.4.1 and XCode 10.
It is possible though, that on XCode 9.4.1, a 64-bit length string was tested on a 64-bit length device/emulator.
But, in case of XCode 10, the testing is being done a 32-bit device/simulator, making case 1(above) valid.

Puneet Sharma
  • 9,369
  • 1
  • 27
  • 33