I have yet to see documentation of a Swift standard library, where I would expect to find something like a File class or struct with an interface for opening, reading, and writing files. All the usual stuff you expect for File IO. Is there one, or are to depend on NSFileManager and its ilk?
5 Answers
Here's a way to do it if the file is in your iOS project (hoping this is your situation):
var filePath = Bundle.main.path(forResource: "theFile", ofType: "txt") var data = Data(contentsOf: URL(fileURLWithPath: filePath)) 1 Comment
The Swift standard library does not include this functionality. The standard library mainly contains data structures, low-level types and calls, and semi-built-in language features; I/O beyond print() and readLine() is considered out of scope. I don't really expect this to change in the near future, either.
However, Foundation contains file I/O calls, and the Swift Corelibs project is working hard to reimplement Foundation in pure Swift so it's available everywhere Swift is. The POSIX I/O calls available on every major operating system are also available in Swift, although they're much clumsier to use.
4 Comments
init(contentsOfURL:) throws and writeToURL(_:) throws APIs are the best simple solution for reading and writing files from Swift.Often in apps you'll be using UIDocument and other iCloud linked ways of saving files, but in the Swift blog Apple uses examples based on C and POSIX for opening and saving files. So they have in one example:
let fd = open("/tmp/scratch.txt", O_WRONLY|O_CREAT, 0o666) if fd < 0 { perror("could not open /tmp/scratch.txt") } else { let text = "Hello World" write(fd, text, text.characters.count) close(fd) } And it looks very Swift like, but whether you want to use this over and above the Cocoa framework I don't know.
NSFileManagerAPI and C API, I can't see any reason to make new Swift APIlet fh = File.open("path"); while var line = fh.readline() { ... }; fh.close().