How to use Optionals to stop a compiler error in Swift [duplicate]

旧时模样 提交于 2019-12-20 06:07:41

问题


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”)
        }

回答1:


  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)


来源:https://stackoverflow.com/questions/41358964/how-to-use-optionals-to-stop-a-compiler-error-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!