- fraction is String not String? so you don't have to use fraction?
- components return [] not []?, so you can use fractionArray without unwrap anything
- the only thing you have to unwrap is numerator and denominator, their type is Double?
- Thanks @OOPer, should check denominator != 0
- 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)