How do I get user input in Swift?

Hi


I'm a computer science teacher in the UK. I currently use Python to teach my courses as all our exam board courses are focused on this language, although we are free to pick other languages. I'm also relatively new to Swift.


Most of the tasks we are set by the exam boards revolve around getting data from a user, manipulating the data and producing an output. They are very much REPL based tasks without a GUI, until you get to A Level.


In Python I would get an input from a user with a simple input and I could then use that value.

eg

name = input("What is your name")

print("Hello", name)


How would I do this in Swift using Xcode?


I know that if I was making an iOS app I would need a UIText field, a label and a button but that all adds a lot of cognitive overload for new, young students. Is there any way of ignoring the UI and just having simple programms running in the terminal?


If I can solve this then I will be able to abandon Python and teach Swift all the way through from age 11 to 18.

Accepted Reply

Please see the Swift Standard Library documentation for the input and output methods you're looking for.


Simple example should be

if let str = readLine() {
   print(str)
}

aassuming I'm sufficiently awake right now.


One of the targets in Xcode should still be "command line tool", and you can set the language to Swift. That should get you your basic non-GUI task, the sort of thing you run from the terminal window.

Replies

Please see the Swift Standard Library documentation for the input and output methods you're looking for.


Simple example should be

if let str = readLine() {
   print(str)
}

aassuming I'm sufficiently awake right now.


One of the targets in Xcode should still be "command line tool", and you can set the language to Swift. That should get you your basic non-GUI task, the sort of thing you run from the terminal window.