Swift - Read/write array of arrays to/from file

atirit picture atirit · Jun 2, 2016 · Viewed 10k times · Source

Here are my files.

How can I write this array:

var listOfTasks = [["Hi", "Hello", "12:00"],["Hey there", "What's up?", "3:17"]]

to a .txt file (file.txt)? I know there are other questions about this, but they're in other languages (not Swift). I'd like for it to work on an actual iPhone. I'm happy to provide additional information if necessary. I'm new to Swift, so excuse my question if it seems too simple. NOTE: I am asking specifically about arrays containing arrays.

Thanks in advance!

Answer

redent84 picture redent84 · Jun 5, 2016

Already answered you in your other question:

Here's a full working Playground sample:

let fileUrl = NSURL(fileURLWithPath: "/tmp/foo.plist") // Your path here
let listOfTasks = [["Hi", "Hello", "12:00"], ["Hey there", "What's up?", "3:17"]]

// Save to file
(listOfTasks as NSArray).writeToURL(fileUrl, atomically: true)

// Read from file
let savedArray = NSArray(contentsOfURL: fileUrl) as! [[String]]

print(savedArray)