August 11, 2020


Xcode: Swift String Input in command line

Swift String Input

Swift String Input

When I first started with Swift, I didn’t think that a Swift String Input would be a issue. But it seems like at the moment there is no methods of getting a string input from terminal or console. You will have to use some Objective C statements to achieve this. They are easily accessible so there is no problem in getting them. You can paste this code and create your own Input method. Here is the Swift String input code:

Please see this for an updated version

 func input() -> String {
   var keyboard = NSFileHandle.fileHandleWithStandardInput()
   var inputData = keyboard.availableData
   return (NSString(data: inputData, encoding: NSUTF8StringEncoding) as! String)

The way you want to use this, is about the same way as with some sort of C language.

 print("Enter> ")
 var string1 = input()
 println("You typed: " + string1)

You can also do it in a “one liner” if you only need to do it once. If you need to do this more than once, I would just go with the first method. Because the printing of the result is also a bit more to it now, as you need to convert it from a NSString to a string.

 println("Enter 2: ")
 var string2 = NSString(data: NSFileHandle.fileHandleWithStandardInput().availableData, encoding: NSUTF8StringEncoding)
 println("You Typed: " + (NSString(string: string2!) as! String))

And that was the second method.

This is one way to get a swift string input. Beware if you just press enter, and pass in an empty string. There might be some trouble in your code.

Here is a link to the swift documentation from Apple

Same as above, but on video.

Thats it. Happy inputing!