Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of how to create a file class with read, write and exists functions
import Foundation
class File {
class func exists (path: String) -> Bool {
return NSFileManager().fileExistsAtPath(path)
}
class func read (path: String, encoding: NSStringEncoding = NSUTF8StringEncoding) -> String? {
if File.exists(path) {
return String.stringWithContentsOfFile(path, encoding: encoding, error: nil)!
}
return nil
}
class func write (path: String, content: String, encoding: NSStringEncoding = NSUTF8StringEncoding) -> Bool {
return content.writeToFile(path, atomically: true, encoding: encoding, error: nil)
}
}
let read : String? = File.read("/path/to/file.txt")
println(read)
let write : Bool = File.write("/path/to/file2.txt", content: "String to write")
println(write)
@neokito

This comment has been minimized.

Copy link

neokito commented Aug 22, 2014

thanks :)

@AnnaLischen

This comment has been minimized.

Copy link

AnnaLischen commented Oct 24, 2014

After the latest update it seems that it will work like this: return String(contentsOfFile: path, encoding: encoding, error: nil)
Does anyone know why?

@KaptenFrans

This comment has been minimized.

Copy link

KaptenFrans commented Nov 18, 2014

I have a problem with the write part. It returns true, but the content is not visible in the file. I've got a text file named data.txt in the root of my project. I'm using the code for an IOS app running through simulator, could that be the problem?

/Seems like it was, ported my code to build for OSX, worked as a charm. Thank you/

@ghost

This comment has been minimized.

Copy link

ghost commented Nov 25, 2014

Hi Friends,
I add something new fades previous data.
I would hope that when you added new data is added to the old data.
So you'd already added protection.
example:
File.write("/path/to/file2.txt", content: "String to write"
File.write("/path/to/file2.txt", content: "Hello world"
File.read("/path/to/file.txt") ---- > print out ->"Hello world"
"String to write" deleted
File.read("/path/to/file.txt") ---> print out -> "String to write
Hello world" must be
How do I do this?

@pomo-mondreganto

This comment has been minimized.

Copy link

pomo-mondreganto commented Nov 30, 2014

And how can I create a new file?

@tbass134

This comment has been minimized.

Copy link

tbass134 commented Mar 14, 2015

String.stringWithContentsOfFile() has been deprecated. You need to use:
String(contentsOfFile: path, encoding: encoding, error: nil)

@Chrisness

This comment has been minimized.

Copy link

Chrisness commented Mar 30, 2015

Thank you so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.