Swift:
קריאת קובץ טקסט

How to: (איך לעשות:)

import Foundation

func readTextFromFile(fileName: String) -> String? {
    guard let path = Bundle.main.path(forResource: fileName, ofType: "txt") else { return nil }
    
    do {
        let text = try String(contentsOfFile: path, encoding: .utf8)
        return text
    } catch {
        print("Error loading file \(fileName): \(error)")
        return nil
    }
}

if let textContent = readTextFromFile(fileName: "example") {
    print(textContent)
}

Sample Output:

// The content of example.txt would be printed here.
Hello, Reader!
Welcome to the world of file handling with Swift.

Deep Dive (צלילה עמוקה):

Reading text files is a basic necessity in programming, dating back to the early days of computers. In Swift, we primarily use the String class and its contentsOfFile initializer to handle this. Alternatives include using Data for non-text files or lower-level C APIs for more control. Details like encoding matter; .utf8 is standard, while others might be used for localization or legacy systems.

See Also (ראה גם):