Skip to content

Instantly share code, notes, and snippets.

@vy-let
Created June 15, 2014 05:05
Show Gist options
  • Save vy-let/e544aaeb4821a996177a to your computer and use it in GitHub Desktop.
Save vy-let/e544aaeb4821a996177a to your computer and use it in GitHub Desktop.
Gets in Swift
//
// 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()
}
@vy-let
Copy link
Author

vy-let commented Jun 15, 2014

Small print: I make no claim that this follows best practices or handles all edge cases.

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