Search code examples
swiftfieldofview

How to remove a variable from the field of view


while true {
print ( """
1. Log in
2. Create new user
3. Quit
""")
if let numberString = readLine(), let number = Int(numberString) {
    print("you entered \(number)")
    break
} else {
    print("Try again")
}
}

It is necessary to use the number variable in the future to compare it. How can it be taken out of sight?

When I try to make a global var something goes wrong:

var numberString: String?
var number: Int?

while true {
print ( """
1. Log in
2. Create new user
3. Quit
""")
if numberString = readLine(), number = Int(numberString) {
    print("you entered \(number)")
    break
} else {
    print("Try again")
}
}

enter image description here


Solution

  • Considering that you are creating a command prompt and that choice has no meaning outside your loop there is no need to make it global. You only need to switch the user selection and decide what to do from there. Note that if you try to break from inside the switch you won't exit your loop as I showed to you in your last question. To allow the compiler to know that you want to break the while loop instead of the switch you need to label your while loop statement, this way you can specify what you want to break when you have a switch inside a loop. Try like this:

    func getValue() -> Int? {
        guard let line = readLine(), let value = Int(line) else {
            return nil
        }
        return value
    }
    
    question: while true {
        print("""
              1. Log in
              2. Create new user
              3. Quit
              """)
        guard let value = getValue() else {
            continue
        }
        switch value {
        case 1:
            print("you have selected number one")
        case 2:
            print("you have selected number two")
        case 3:
            print("Good bye")
            break question
        default:
            print("Try again")
        }
    }