Last active
August 29, 2015 14:17
-
-
Save jinhyung/865f9b3a89563112e14b to your computer and use it in GitHub Desktop.
NSFileHandle Generator for for-loop
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
#!/usr/bin/env swift | |
import Foundation | |
public class _NSFileHandle_Generator: GeneratorType { | |
private let fileHandle: NSFileHandle | |
private var buffer = "" | |
private var previousLine = "" | |
private var newline: String? | |
private init(fileHandle: NSFileHandle) { | |
self.fileHandle = fileHandle | |
} | |
public func next() -> String? { | |
if count(buffer) == 0 { | |
if let nextString = fileHandle.availableString() { | |
buffer = nextString | |
} else { | |
return nil | |
} | |
} | |
if let range = buffer.rangeOfString("\n") { | |
let line = buffer.substringWithRange(Range(start: buffer.startIndex, | |
end: range.startIndex)) | |
newline = previousLine + line | |
buffer = buffer.substringWithRange(Range(start: advance(range.startIndex, 1), | |
end: buffer.endIndex)) | |
} else { | |
previousLine = buffer | |
buffer = "" | |
return next() | |
} | |
return newline | |
} | |
} | |
extension NSFileHandle: SequenceType { | |
public func availableString() -> String? { | |
let data: NSData = self.availableData | |
if data.length == 0 { | |
return nil | |
} | |
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) { | |
return str as String | |
} | |
return nil | |
} | |
public func generate() -> _NSFileHandle_Generator { | |
return _NSFileHandle_Generator(fileHandle: self) | |
} | |
} | |
func main(args: [String]) -> Int32 { | |
let fileHandle = NSFileHandle(forReadingAtPath:args[1] as String)! | |
for line in fileHandle { | |
println(line) | |
} | |
return 0 | |
} | |
let ret = main(Process.arguments) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment