borchero
borchero

Reputation: 6002

Saving Arrays in Swift

I have a question about saving Arrays in Apple's new programming language Swift. In Objective-C I saved data with NSFileManager... but this doesn't work anymore in Swift. So I wanted to ask how I should save an array WITHOUT using NSUserDefaults which isn't really suited for storing a big amount of data. I would really much appreciate any help :]

Upvotes: 1

Views: 1551

Answers (1)

Clement Bisaillon
Clement Bisaillon

Reputation: 5177

First (if your array is not of string type) change it to String:

var notStringArray = [1, 2, 3, 4]
var array: [String] = []

for value in notStringArray{
    array.append(String(value))
}

Then reduce the array to one string:

var array = ["1", "2", "3", "4", "5"] //Ignore this line if your array wasn't of type String and you did the step above
var stringFromArray = reduce(array, "") { $0.isEmpty ? $1 : "\($0)\n\($1)" }

This create an string that looks like this:

"1
 2
 3
 4
 5"

And then to write and read a file add this class at the top of your file:

class File {
    class func open (path: String, utf8: NSStringEncoding = NSUTF8StringEncoding) -> String? {
        var error: NSError?   // 
        return NSFileManager().fileExistsAtPath(path) ? String(contentsOfFile: path, encoding: utf8, error: &error)! : nil
    }
    class func save (path: String, fileContent: String, utf8: NSStringEncoding = NSUTF8StringEncoding) -> Bool {
        var error: NSError?   // 
        return fileContent.writeToFile(path, atomically: true, encoding: utf8, error: &error)
    }

}

(Don't forget to import UIKit)

To save to a file:

let didSave = File.save("DirectoryOfFile", content: stringFromArray) 
if didSave {
    println("file saved") 
} else {
    println("error saving file") 
} 

To get it back:

var stringFromFile = ""

if let loadData = File.open("DirectoryOfFile") {
    stringFromFile = loadData
} else {
    println("error reading file")
}  

To put it back in an array:

var newArray: [String] = [] //Creates empty string array
newArray = stringFromFile.componentsSeparatedByString("\n")

And there you have it

Upvotes: 2

Related Questions