I'm just starting learning Swift and to teach myself I'm making a simple command line app. It will eventually connect to an online data source but initially I want to load data from a file. I've seen various guides on reading the contents of a file in Swift but none of them seem to work for me. Here is my app so far:
import Foundation // Set the file path let path = "/Users/username/workspace/Swift/sis/sis/data.json" do { // Get the contents let contents = try String(contentsOfFile: path, encoding: .utf8) print(contents) } catch let error as NSError { print("Ooops! Something went wrong: \(error)") } Running it outputs:
Ooops! Something went wrong: Error Domain=NSCocoaErrorDomain Code=260 "The file “data.json” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Users/username/workspace/Swift/sis/sis/data.json, NSUnderlyingError=0x100e19a50 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}} However on the terminal:
$ ls -l /Users/username/workspace/Swift/sis/sis/data.json -rwxrwxrwx@ 1 username staff 165563 16 Jan 17:14 /Users/username/workspace/Swift/sis/sis/data.json (yeah I relaxed the permissions somewhat just in case that was the problem)
The only slightly anomalous thing I noticed (aside from the inaccurate assertion that the file doesn't exist) was that when I copy and past the path from the XCode output into iTerm2 it puts spaces between each path component:
(pasted as an image as copying it and pasting it back into this form seems to hide the spaces - this is probably irrelevant anyway)
Any help figuring this out would be really appreciated!


let path = ...line. Deleting and retyping that line should fix the problem.print(Array(path.unicodeScalars))to see the cause of the problem.