Skip to content

Instantly share code, notes, and snippets.

@douglashill
Last active September 17, 2018 09:02
Show Gist options
  • Save douglashill/9f5be274ec72bbc77c5c6039e076fb48 to your computer and use it in GitHub Desktop.
Save douglashill/9f5be274ec72bbc77c5c6039e076fb48 to your computer and use it in GitHub Desktop.
Generating an enum to ensure only defined localised string keys are used. For development on Apple platforms.
// Douglas Hill, February 2018
import Foundation
/// Returns a localised string with the key as an enum case so the compiler checks it exists.
/// The enum should be automatically generated using UpdateLocalisedStringKeys.swift.
public func localisedString(_ key: LocalisedStringKey) -> String {
return Bundle.main.localizedString(forKey: key.rawValue, value: nil, table: nil)
}
#!/usr/bin/env xcrun --sdk macosx swift
// Douglas Hill, February 2018
// Generates a Swift source file defining an enum with all possible localised string keys.
// Run this in a script build phase before ‘Compile Sources’.
import Foundation
extension URL {
public func appendingPathComponents(_ pathComponents: [String]) -> URL {
return pathComponents.enumerated().reduce(self) { url, pair in
return url.appendingPathComponent(pair.element, isDirectory: pair.offset + 1 < pathComponents.count)
}
}
}
let projectDirectory = URL(fileURLWithPath: ProcessInfo.processInfo.environment["PROJECT_DIR"]!)
let inputStringsFile = projectDirectory.appendingPathComponents(["Somewhere", "en.lproj", "Localizable.strings"])
let outputSwiftFile = projectDirectory.appendingPathComponents(["Somewhere", "LocalisedStringKeys.swift"])
let stringsDictionary = NSDictionary(contentsOf: inputStringsFile)!
let keys = stringsDictionary.allKeys as! [String]
let enumCases = keys.sorted().map { " case \($0)" }.joined(separator: "\n")
let contents = """
// This file was automatically generated from \((#file as NSString).lastPathComponent).
public enum LocalisedStringKey: String {
\(enumCases)
}
"""
let oldContents = try? String(contentsOf: outputSwiftFile)
if contents != oldContents {
try! contents.write(to: outputSwiftFile, atomically: false, encoding: .utf8)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment