Last active
August 29, 2015 14:09
-
-
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
This file contains hidden or 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
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 | |
} | |
} | |
} | |
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
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.