Created
June 15, 2014 05:05
-
-
Save vy-let/e544aaeb4821a996177a to your computer and use it in GitHub Desktop.
Gets in Swift
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
// | |
// gets.swift | |
// smilef | |
// | |
// Created by Talus Baddley on 2014-6-5. | |
// Copyright (c) 2014 Eightt. All rights reserved. | |
// | |
// This is to demonstrate a simple, safe gets() implementation | |
// in Swift, that automatically buffers input on demand and | |
// always splits on newline. | |
import Foundation | |
// Just everything the system has buffered & waiting: | |
func slurpFromStdin() -> NSString { | |
var keyboard = NSFileHandle.fileHandleWithStandardInput() | |
var inputData = keyboard.availableData | |
return NSString(data: inputData, encoding:NSUTF8StringEncoding) | |
} | |
// That is, it returns a block which takes no arguments | |
// and which itself returns an NSString. | |
func makeLineReader() -> ()->NSString { | |
var textBuffer: NSString = NSString() | |
return { | |
while textBuffer.rangeOfString("\n").location == NSNotFound { | |
textBuffer = textBuffer.stringByAppendingString(slurpFromStdin()) | |
} | |
let ross = textBuffer.rangeOfString("\n") | |
let firstFullLine = textBuffer.substringToIndex(ross.location) | |
textBuffer = textBuffer.substringFromIndex(ross.location + ross.length) | |
return firstFullLine | |
} | |
} | |
let staticLineReader = makeLineReader() | |
// Simply invoke the static line reader block: | |
func gets() -> String { | |
return staticLineReader() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Small print: I make no claim that this follows best practices or handles all edge cases.