Skip to content
otto-schnurr edited this page Sep 3, 2014 · 19 revisions

Types

LineOfText

Declaration

typealias LineOfText = String

Discussion

A collection of characters typically ending with a newline. The last line of a file might not contain a newline.

The FileInput class is a Sequence of LineOfText objects.

Creating an Input Sequence

input()

Parses input from the command line.

Declaration

func input() -> FileInput

Discussion

Returns a FileInput sequence that iterates over lines of all file paths listed in command line arguments. If that list is empty then standard input is used.

let lineCount = countElements( input() )
println( "\(lineCount) lines" )

A file path of "-" is replaced with standard input.

FileInput()

Constructs a sequence that iterates lines of standard input.

Declaration

init()

Discussion

Creating FileInput using this constructor:

var standardInput = FileInput()

is equivalent to using a "-" file path:

var equivalentInput = FileInput( filePath: "-" )

FileInput( filePath: )

Constructs a sequence that iterates lines of a file.

Declaration

init( filePath: String )

Discussion

The resulting FileInput sequence retrieves one line of data at a time:

for line in FileInput( filePath: "data.txt" ) {
    processNextLineOfData( line )
}

A file path of "-" is replaced with standard input.

FileInput( filePaths: )

Constructs a sequence that iterates lines over a collection of files.

Declaration

init( filePaths: [String] )

Discussion

The resulting FileInput sequence retrieves lines from "a.txt then "b.txt":

let files = [ "a.txt", "b.txt" ]
for line in FileInput( filePaths: files ) {
    processNextLineOfData( line )
}

Each file path of "-" is replaced with standard input.

Querying an Input Sequence

var filePath { get }

An optional string indicating where the previous line of text came from.

Declaration

var filePath: String? { get }

Discussion

Use this property to query what file path was used in the last call to nextLine(). The value will be nil when the sequence has been exhausted.

var lines = input()
for line in lines {
    // Newline delimiters are not removed from line.
    print( "\(lines.filePath!): \(line)" )
}

nextLine() -> LineOfText?

Returns the next line of text in the sequence.

Declaration

func nextLine() -> LineOfText?

Discussion

Use this method to retrieve the next line of input. The value will be nil when the sequence has been exhausted.

if let firstLine = input().nextLine() {
    processFirstLine( firstLine )
}

This is the method used by for-in loops.

Clone this wiki locally