Lion Lion - 11 months ago 62
Swift Question

Forced unwrapping of optional causes crash in Filter

I am having trouble with this method; I am getting a "fatal error: unexpectedly found nil while unwrapping an Optional value" error.

let filtererArr = structArrayWithNoOptionals.filter({
return getFloatNumberFromPriceString(removeCommaFromPriceString($0.totalFare!)) >= minPrice && getFloatNumberFromPriceString(removeCommaFromPriceString($0.totalFare!)) <= maxPrice

How do I fix this to prevent it from crashing?

Answer Source

I always try to avoid force unwrapping when possible, in your case you can use guard let or if let to unwrap it

Change your code this

let filtererArr = structArrayWithNoOptionals.filter({
    guard let totalFare = $0.totalFare else { return false }
    return getFloatNumberFromPriceString(removeCommaFromPriceString(totalFare)) >= minPrice &&
        getFloatNumberFromPriceString(removeCommaFromPriceString(totalFare)) <= maxPrice