Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dmytro-anokhin/640f2739ef369da731d6d811bdcac16e to your computer and use it in GitHub Desktop.
Save dmytro-anokhin/640f2739ef369da731d6d811bdcac16e to your computer and use it in GitHub Desktop.
protocol CitiesSource {
func loadCities() -> [String]
}
struct CitiesFile: CitiesSource {
let location: URL
init(location: URL) {
self.location = location
}
/// Looks up for `cities` file in the main bundle
init?() {
guard let location = Bundle.main.url(forResource: "cities", withExtension: nil) else {
assertionFailure("cities file is not in the main bundle")
return nil
}
self.init(location: location)
}
func loadCities() -> [String] {
do {
let data = try Data(contentsOf: location)
let string = String(data: data, encoding: .utf8)
return string?.components(separatedBy: .newlines) ?? []
}
catch {
return []
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment