Swift REPL (macOS Terminal): `readLine()`

When I use the Swift REPL in macOS Terminal app, why does readLine() in a swift file not work properly but then does so in Xcode? I was trying to create an interactive terminal app that captures user input and then chooses what to do next based on that input.

Let’s say that I have a swift file (“example.swift”) on my desktop with the following code (shown below). How would I run it in the Terminal app so that it is actually interactive and will accept user input as much as requested during the app’s execution?

func askUserQuestion () {
   print("Are you happy or sad? (HAPPY / SAD)") 
   if let userInput = readLine() 
   if userInput.uppercased() == "HAPPY" {
      print("Yay! I'm glad that you're happy!") 
   } else if userInput.uppercased() == "SAD" {
      print("Uh-oh! I'm hoping that you'll feel better soon.") 
   } else {
      print("Umm, I'm not sure if that is happy or sad.") 


I don’t think readLine works directly in the REPL, but if you want to run a swift file from the terminal, you can compile it and run the binary.
To do so, you use the following syntax:
swiftc -o [name_of_binary] [name_of_file]

So if you have a file called “example.swift” and you want to compile it to a binary called example, you would run the following:
swiftc -o example example.swift

1 Like