Wednesday, December 31, 2014

Swift File Manipulation

When you start writing in a new language it is always an adventure.

When your code starts to work it can be thrilling and when you can't seem to get something to work it can be very frustrating.

But as you dig in deeper there are occasions when you try to do something and it works, but you're not sure why.

This can happen when you start following advice but use Cargo Cult logic to find the "right" syntax.

This is exactly what I have done so far with Swift.

I found that it was difficult to get the answer to the question: how do I read & write to a file in the UNIX file system?

It actually took a considerable amount of digging and experimentation to accomplish what I take for granted as a very common thing that I do with perl, Java or Python on a daily basis.

That all being said I actually got it working on a rudimentary level.  I can read and write to a specific file in a predetermined location.

But that's all that I understand so far.  I very much feel like a neolithic man poking an obelisk from space with a bone since there is a LOT going on here that I do not understand.

You will note for example the use of dirs and dirz (distinct var names) which I resorted to while debugging example code from someone else.

So I figured that I would share my source code since this is just something I have running in a Playground file:


// Playground - noun: a place where people can play

import Cocoa

let file = "test.txt"

let dirs: [String]? = 
    NSSearchPathForDirectoriesInDomains(
        NSSearchPathDirectory.DocumentDirectory, 
        NSSearchPathDomainMask.AllDomainsMask, 
        true) as? [String]

println(dirs)

if (dirs != nil) {
    
    let directories:[String] = dirs!

    let dirz = directories[0]
    
    let path = dirz.stringByAppendingPathComponent(file)
    
    println(path)
    
    println("I usually fiddle with this string to force a page recompile")
    
    //reading
    var error:NSError?
    
    //reading
    let readText = String(contentsOfFile: path, 
                          encoding:NSUTF8StringEncoding, 
                          error: &error)
    
    if let theError = error {
        print("\(theError.localizedDescription)")
    }
 
    println(readText)
    
    let text = readText! + 
               "this is added to the file every time we run\n"
    
    //writing
    text.writeToFile(path, 
                     atomically: false, 
                     encoding: NSUTF8StringEncoding, 
                     error: nil);
}

No comments:

Post a Comment