Skip to content

Instantly share code, notes, and snippets.

@kennygoff
Last active August 29, 2015 14:02
Show Gist options
  • Save kennygoff/93a7fc4a496a805810f3 to your computer and use it in GitHub Desktop.
Save kennygoff/93a7fc4a496a805810f3 to your computer and use it in GitHub Desktop.
Swift getline
/**
* Unfortunately, this is the only working method I've found to get
* command line user input. Right in the Swift book, Apple writes:
* "You don’t need to import a separate library for functionality
* like input/output or string handling."
* I shouldn't need to define this function.
* As I learn more about Swift I hope to replace this. #FingersCrossed
* [via http://stackoverflow.com/a/24021467/1235893]
*
* <3 @kennygoff
*/
// Usage: var input = getline()
func getline() -> String {
var keyboard = NSFileHandle.fileHandleWithStandardInput()
var inputData = keyboard.availableData
var line = NSString(data: inputData, encoding:NSUTF8StringEncoding)
# Remove the newline character
return line.substringToIndex(line.length-1)
}
@kennygoff
Copy link
Author

This can obviously be updated to specifically trim a newline character, rather than just hackily removing the last character.

@rcmaniac25
Copy link

That's horrible... Even C has an easier to read a newline... though it may not be any shorter.

@zaksoup
Copy link

zaksoup commented Jun 11, 2014

@rcmaniac25 Swift isn't really meant to be reading from the keyboard so it's pretty understandable that C does it better...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment