Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get user input in Apple's Swift language in a command line tool? [duplicate]

Tags:

swift

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
like image 783
Jeremy M Avatar asked Jun 09 '14 01:06

Jeremy M


People also ask

How do I get user input in Swift?

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.

How do you readLine in Swift?

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.


1 Answers

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.

like image 123
Joseph Mark Avatar answered Oct 03 '22 02:10

Joseph Mark