If you import Glibc on Linux and Darwin.C on macOS, you can read one line at a time using the getline function.
This requires the c interop bit, but you can wrap it to represent a more Swifty interface. For example, the following function returns a generator that iterates over lines read from a file stream:
#if os(Linux) import Glibc #else import Darwin.C #endif func lineGenerator(file:UnsafeMutablePointer<FILE>) -> AnyIterator<String> { return AnyIterator { () -> String? in var line:UnsafeMutablePointer<CChar>? = nil var linecap:Int = 0 defer { free(line) } let charactersWritten = getline(&line, &linecap, file) if charactersWritten > 0 { guard let line = line else { return nil } return String(validatingUTF8: line) } else { return nil } } }
This works on Swift 3. You can find a small example project swiftecho that uses this from the command line.
algal
source share