Skip to content

Instantly share code, notes, and snippets.

@zorn
Last active August 29, 2015 14:09
Show Gist options
  • Save zorn/81597fc1552f113e262b to your computer and use it in GitHub Desktop.
Save zorn/81597fc1552f113e262b to your computer and use it in GitHub Desktop.
Help me write a simple Swift function to load a string from a file
import Foundation
struct ShowdownDataLoader {
// So this is a simple function that should return a string from a file but it sucks.
// if feels way to verbose and I hate all the indentation. Please show me how I might
// be able to refactor it.
// Please be additive to the GIST with your suggestion so others can see the origianl.
func loadPokemonJSONString() -> String? {
let mainBundle = NSBundle.mainBundle()
if let pathToJSON = mainBundle.pathForResource("pokedex", ofType: "js") {
var stringError: NSError?
if let jsonString = String(contentsOfFile: pathToJSON, encoding: NSUTF8StringEncoding, error: &stringError) {
return jsonString
} else {
var errorMessage = "Error not returned"
if let error = stringError {
errorMessage = error.localizedDescription
}
NSLog("Error reading String from file: \(pathToJSON) error: \(errorMessage)")
return nil;
}
} else {
NSLog("Could not find path to JSON resource")
return nil
}
}
}
@brianjgeiger
Copy link

I suspect you're looking for a Swiftier solution, but I am not Swifty yet. That being said, a more generic way of refactoring is to break up the problem into more functions.

import Foundation

struct ShowdownDataLoader {

    func loadPokemonJSONString() -> String? {
        let mainBundle = NSBundle.mainBundle()
        if let pathToJSON = mainBundle.pathForResource("pokedex", ofType: "js") {
            return loadJSONFromPath(pathToJSON)
        } else {
            NSLog("Could not find path to JSON resource")
            return nil
        }
    }

    func loadJSONFromPath(pathToJSON: String) -> String? {
        var stringError: NSError?
        if let jsonString = String(contentsOfFile: pathToJSON, encoding: NSUTF8StringEncoding, error: &stringError) {
            return jsonString
        } else {
            var errorMessage = "Error not returned"
            if let error = stringError {
                errorMessage = error.localizedDescription
            }
            NSLog("Error reading String from file: \(pathToJSON) error: \(errorMessage)")
            return nil;
        }
    }
}

@zorn
Copy link
Author

zorn commented Nov 18, 2014

Thanks for the feedback. The refactor is an improvement but still doesn't feel elegant. Not sure it ever will as long as I have to call ObjC-based APIs. Thanks for taking the time to give me some feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment