SWIFT: Make program wait for input

  • Thread starter Thread starter RoboNerd
  • Start date Start date
  • Tags Tags
    Input Program
Click For Summary
SUMMARY

The discussion centers on a Swift programming issue where the user's input is not being captured in a console application for a blackjack game. The problem arises when using the readLine() function in an interactive playground environment, which does not wait for user input and returns an empty string. The solution is to transition to a command line tool, where the readLine() function operates correctly, allowing the program to pause for user input as intended.

PREREQUISITES
  • Understanding of Swift programming language
  • Familiarity with console applications
  • Knowledge of the readLine() function in Swift
  • Experience with command line tools and environments
NEXT STEPS
  • Explore Swift's readLine() function in detail
  • Learn about setting up command line tools in Xcode
  • Investigate differences between playgrounds and command line execution in Swift
  • Research best practices for user input handling in console applications
USEFUL FOR

Swift developers, especially those creating console applications, and anyone troubleshooting input handling issues in interactive environments.

RoboNerd
Messages
410
Reaction score
11
Hi everyone.

I am working on a blackjack game using swift, and I have need to get the user's input from a console. While my code (which is attached below) works in theory, my program does not wait for the user to type some input in the console. Instead, it quickly passes over it and returns an empty string.

If anyone could provide some input that would be great.
My code is shown below:

"""
Code:
func input() -> String
{
    print("Checkpoint 1")
    let input = readLine(stripNewline: true)
    print("Checkpoint 2")
    if (input != nil)
    {
        return input!
    }
    else
    {
        return ""
    }
}

""""

My console output is as following:
"
Curent hand value is: 10. Do you want another card? (yes/no):

Checkpoint 1

Checkpoint 2
"


-----

My program calls the input() function after it asks the user "Do you want another card?" and as one can see by the printing of the checkpoint lines, the console does not stop and wait.

Could anyone please provide some input as to what is going on?

Thanks in advance.
 
Last edited by a moderator:
Technology news on Phys.org
What execution environment? In interactive playground environments or similar you may well find that readLine() always assumes end of file.
 
  • Like
Likes   Reactions: RoboNerd
It is a playground. Thanks for the help!

I shifted to a command line tool and everything works fine now!
 

Similar threads

Replies
1
Views
2K
  • · Replies 14 ·
Replies
14
Views
35K
Replies
55
Views
7K
Replies
17
Views
10K
  • · Replies 3 ·
Replies
3
Views
2K
Replies
3
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
Replies
1
Views
3K
Replies
2
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K