Search code examples
swiftoption-typeunwrap

How can I safety unwrap an optional with a default value using `coalescing unwrapping` - Not workig - Swift


How can I safety unwrap the first optional item from arrayOfStrings to get just the pounds with a default value of 0 using coalescing unwrapping?

Based on the code below, what I want is to be able to get the 5 but if this would be empty assign 0 as the default value, for instance if the measurement is "lb. 8oz." I want pounds to get the value of 0.

In the following example, I do get 5 but it crashes if I change measurement from "5lb. 8oz." to "lb. 8oz."

let measurement = "5lb. 8oz."

let arrayOfStrings:[String] = measurement.components(separatedBy: "l")
print("Array of Strings: \(arrayOfStrings)") //Output: Array of Strings: ["5", "b. 8oz."]

let pounds = Double(arrayOfStrings[0] ?? "0") 
print("Pounds \(pounds!)") //Output: Pounds 5.0

Error: When changing measurement to "lb. 8oz."

Fatal error: Unexpectedly found nil while unwrapping an Optional value

FYI - I'm looking for a single line solution, I know how to do it using if let or guard.


Solution

  • You can unwrap the access of the array and the conversion to Double

    let pounds = Double(arrayOfStrings.first ?? "0") ?? 0.0