Created
July 15, 2015 19:53
This file contains 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
//: Playground - noun: a place where people can play | |
import Foundation | |
// This is a fake implementation mimicking the behavior of having a Localizable.string | |
// This is used here to be able to test the code easily in a Playground | |
func localize(key: String) -> String { | |
return [ | |
"alert.title": "Titre d'Alerte", | |
"alert.message": "Message d'Alerte", | |
"greetings.text": "My name is %@ and I'm %d." | |
][key] ?? key | |
} | |
// The real implementation would instead use Localizable.strings: | |
//func localize(key: String) -> String { | |
// return NSLocalizedString(key, comment: "") | |
//} | |
// MARK: Version 1 | |
enum L10n_v1 : String { | |
// >>> GENERATE THIS USING A SCRIPT | |
case AlertTitle = "alert.title" | |
case AlertMessage = "alert.message" | |
case Presentation = "greetings.text" | |
// <<< --- | |
func format(args: CVarArgType...) -> String { | |
let format = localize(self.rawValue) | |
return String(format: format, arguments: args) | |
} | |
var string : String { | |
return localize(self.rawValue) | |
} | |
} | |
L10n_v1.AlertTitle.string | |
L10n_v1.Presentation.format("David", 29) | |
// MARK: Version 2 | |
enum L10n_v2 : CustomStringConvertible { | |
// >>> GENERATE THIS USING A SCRIPT | |
case AlertTitle | |
case AlertMessage | |
case Presentation(String, Int) | |
var description : String { | |
switch self { | |
case .AlertTitle: | |
return tr("alert.title") | |
case .AlertMessage: | |
return tr("alert.message") | |
case .Presentation(let first, let last): | |
return tr("greetings.text", first, last) | |
} | |
} | |
// <<< --- | |
private func tr(key: String, _ args: CVarArgType...) -> String { | |
let format = localize(key) | |
return String(format: format, arguments: args) | |
} | |
} | |
func tr(key: L10n_v2) -> String { return key.description } | |
tr(.AlertTitle) | |
tr(.Presentation("David", 29)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment