I am new to Apple programming and I thought I'd try out Swift, but I have no idea how to get user input and store it in a variable. I am looking for the simplest way to do this, something like input() and raw_input() in Python.
# Something like this (Python code)
name = raw_input() # name is a string
print "Your name is ", name
number = input() # number is an int or float
Getting input from the user in Swift is very easy with the help of the readLine() function. This function returns a string of characters which is read from the standard input at the end of the current line.
To read number from console input in Swift, use readLine() and Int() functions. readLine() function returns the string of characters read from standard input, and Int() converts this string to integer. Converting to a number is not limited to converting the read string into an integer.
This is actually not easy in Swift at this point. The simplest way is probably the Objective-C way, using an NSFileHandle with standard input:
import Foundation
var fh = NSFileHandle.fileHandleWithStandardInput()
println("What is your name?")
if let data = fh.availableData {
var str = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Your name is \(str)")
}
Or for continuous input:
println("I will repeat strings back at you:")
waitingOnInput: while true {
if let data = fh.availableData {
var str = NSString(data: data, encoding: NSUTF8StringEncoding)
println(str)
}
}
The possible encodings are shown here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With