Created
November 24, 2015 05:52
-
-
Save eldesperado/319e51f8fdb4cacc223f to your computer and use it in GitHub Desktop.
HackerRank in Swift - StdIn (http://mgrebenets.github.io/hackerrank/2015/03/15/hackerrank-in-swift---io/)
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
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