Created
June 18, 2015 13:21
-
-
Save kostiakoval/558c0f695593d0065d3f to your computer and use it in GitHub Desktop.
FileHelper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct DataEncodable<T> { | |
static func encode(var value: T) -> NSData { | |
return withUnsafePointer(&value) { NSData(bytes: $0, length: sizeof(T)) } | |
} | |
static func decode(data: NSData) -> T { | |
let pointer = UnsafeMutablePointer<T>.alloc(sizeof(T)) | |
data.getBytes(pointer, length: sizeof(T)) | |
return pointer.move() | |
} | |
} | |
struct File { | |
static func save<T>(x: T, toFile file: String) -> Bool { | |
let url = FileHelper.filePath(file) | |
let data = DataEncodable.encode(x) | |
return data.writeToFile(url, atomically: true) | |
} | |
static func load<T>(file: String) -> T? { | |
let url = FileHelper.filePath(file) | |
let data = NSData(contentsOfFile: url) | |
return data.map { DataEncodable.decode($0) } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FileHelper { | |
public static var documentDirectory: String { | |
return directoryPath(.DocumentDirectory) | |
} | |
public static func filePath(file :String, directory: NSSearchPathDirectory = .DocumentDirectory) -> String { | |
return directoryPath(directory).stringByAppendingPathComponent(file) | |
} | |
// MARK:- Private | |
private static func directoryPath(dir: NSSearchPathDirectory) -> String { | |
return NSSearchPathForDirectoriesInDomains(dir, .UserDomainMask, true).first as! String | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Cat: Creature { | |
let name: String | |
} | |
var cat = Cat(name: "A") | |
let data = File.save(cat, toFile: "A.txt") | |
let cat1: Cat? = File.load("A.txt") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment