Read String from file in Swift

October 16, 2017

In this example you can use String() constructor to read String directly from the file you specified.

import Cocoa

let home = FileManager.default.homeDirectoryForCurrentUser
let playgroundPath = "Documents/dev/xcode/DatePicker/c"

// Get your playground URL
let playgroundURL = home.appendingPathComponent(playgroundPath)

let path = playgroundURL.appendingPathComponent("test.txt").path

do {

let contents = try String(contentsOfFile: path, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))

} catch let error as Error{