Code Snippet: Print a File Line-by-Line

From Coder Merlin
Revision as of 20:45, 20 January 2019 by Chukwuemeka-tinashe (talk | contribs) (Created page with "== Swift == <syntaxhighlight lang="swift"> import Foundation // Determine the file name let filename = "main.swift" // Read the contents of the specified file let contents =...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

Swift[edit]

import Foundation

// Determine the file name
let filename = "main.swift"

// Read the contents of the specified file
let contents = try! String(contentsOfFile: filename)

// Split the file into separate lines
let lines = contents.split(separator:"\n")

// Define a variable to track the current line number
// Iterate over each line and print the line preceded
// by the line number
var lineNumber = 1
for line in lines {
    print("\(lineNumber): \(line)")
    lineNumber += 1
}