How to use Optionals to stop a compiler error in Swift

Solutions Collect From Internet About “How to use Optionals to stop a compiler error in Swift”

  1. fraction is String not String? so you don’t have to use fraction?
  2. components return [] not []?, so you can use fractionArray without unwrap anything
  3. the only thing you have to unwrap is numerator and denominator, their type is Double?
  4. Thanks @OOPer, should check denominator != 0
  5. Thanks @Martin R, should check fractionArray.count == 2

so I’ll refactor to the following code:

let fraction = "15/8"
let fractionArray = fraction.components(separatedBy: "/")
guard let numerator = Double(fractionArray[0]), 
    let denominator = Double(fractionArray[1]),
    denominator != 0,
    fractionArray.count == 2 else {
    print("Invalid. Re-enter fraction, or denominator == 0, or fractionArray.count != 2")
    return
}
let linearFactor = numerator / denominator
print(numerator, "/", denominator, " = ", linearFactor)