Skip to content

Instantly share code, notes, and snippets.

@eldesperado
Created November 24, 2015 05:52
Show Gist options
  • Save eldesperado/319e51f8fdb4cacc223f to your computer and use it in GitHub Desktop.
Save eldesperado/319e51f8fdb4cacc223f to your computer and use it in GitHub Desktop.
import Foundation
// MARK: Standard Input
/// Reads a line from standard input
///:returns: string form stdin
public func getLine() -> String {
var buf = String()
var c = getchar()
// 10 is ascii code for newline
while c != EOF && c != 10 {
buf.append(UnicodeScalar(UInt32(c)))
c = getchar()
}
return buf
}
public func readLn<T>() -> T {
if (T.self as? String.Type != nil) {
return getLine()
} else if (T.self as? Int.Type != nil) {
return getLine().toInt()!
} else if (T.self as? [String].Type != nil) {
return getLine().componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
} else if (T.self as? [Int].Type != nil) {
let words: [String] = readLn()
return words.map { $0.toInt()! }
} else {
return getLine()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment