Last active
August 29, 2015 14:02
-
-
Save kennygoff/93a7fc4a496a805810f3 to your computer and use it in GitHub Desktop.
Swift getline
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) | |
} |
That's horrible... Even C has an easier to read a newline... though it may not be any shorter.
@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
This can obviously be updated to specifically trim a newline character, rather than just hackily removing the last character.