I want a way to detect input errors in a string and notify the user. Take the following example:
let fraction = "15/8"
let fractionArray = fraction.components(separatedBy: "/")
let numerator = Double(fractionArray[0])
let denominator = Double(fractionArray[1])
var linearFactor = numerator! / denominator!
print(numerator!, "/", denominator!, " = ", linearFactor)
But if I force unwrap, invalid characters in the string will force a compile error and I’d rather notify the user that the input string contains an invalid fraction. Optional chaining seems like the way to go but I can’t get the syntax right.
In my code (below), I place the optional chaining operator next to the array as shown including fraction?.components(separatedBy: “/“)
but Fix-it tells me to delete it.
If there is a better way than optional chaining to address this problem can someone please explain what I might have missed when I searched for answers here so I can make the code work ? Thanks
let fraction = “15/8”
if let fractionArray = fraction?.components(separatedBy: “/“) {
let numerator = Double(fractionArray[0])
let denominator = Double(fractionArray[1])
var linearFactor = numerator / denominator
print(numerator, "/", denominator, " = ", linearFactor)
} else {
print(“Invalid. Re-enter fraction”)
}