0

I'm trying to cast A double? to String.

I've tried

let price = eventDataFromPrevious.dtPrice as? String
eventPriceLabel.text = price!  + "€"

but I get this error when I get to that VC:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

My eventDataFromPrevious object looks like this in a dump:

▿ LuxEvent.EventData #0
  - idEvent: "53"
  - dtTitle: "Anniversaire de Moon"
  - dtStartDate: "2020-4-15 20:0:0"
  - dtEndDate: "2020-4-16 5:0:0"
  ▿ dtPrice: Optional(1000.0)
    - some: 1000.0
  - dtAddress: "56, Avenue Frantz Clement, Mondorf-les-Bains, Luxembourg"
  - fiCategory: "8"
  - dtCity: ""
  - dtDescription: "Soirée déguisée, apportez tous vos chiens et chiennes, et pas besoin de capotes!"
  - dtLong: "6.27737"
  - dtLat: "49.503963"
  - dtImage: "defaultImage.jpg"

Note that I have to have dtPrice as a Double? because the price can be nil if an event is free.

Thanks for the help in advance!

Wilson Silva
  • 1,324
  • 1
  • 14
  • 25
  • 1
    watch here: – Scoopex Mar 30 '20 at 22:10
  • Thanks, for some reason I didn't find that post, sorry! – Wilson Silva Mar 30 '20 at 22:17
  • 1
    On a side note, even in cases where this would work there's no point in using `as?` if you're going to force unwrap it on the next line anyway. Either just use `as!` in the first place if you're 100% confident it will never be nil, or conditionally unwrap it so you can safely handle potential nil values. – John Montgomery Mar 30 '20 at 22:21

1 Answers1

0

You can't coerce a Double? to a String. It's better to instead use String(describing:), e.g.

let price = String(describing: eventDataFromPrevious.dtPrice ?? 0.0) // 0.0 for "free"
eventPriceLabel.text = price + "€"

This also avoids force-unwrapping the result, since String(describing:) returns a String instead of a String?.

Alternatively, if you want to show "Free" instead of "0.0€", you can do the following:

if let dtPrice = eventDataFromPrevious.dtPrice {
    let price = String(describing: dtPrice)
    eventPriceLabel.text = price + "€"
} else {
    eventPriceLabel.text = "Free"
}
atirit
  • 1,492
  • 5
  • 18
  • 30
  • If formatting a number for UI, you should use `NumberFormatter`, not `String(describing:)`. – Rob Mar 30 '20 at 22:19