Skip to content

Instantly share code, notes, and snippets.

@thefotes
Created January 17, 2016 13:33
Show Gist options
  • Save thefotes/c908e3caa5a5904f331c to your computer and use it in GitHub Desktop.
Save thefotes/c908e3caa5a5904f331c to your computer and use it in GitHub Desktop.
Cleaner localized strings with Swift protocols and enums.
import Foundation
// Localized string struct that has single static method which accepts a `Localizeable` value.
struct LocalizedString {
// Usage: LocalizedString.localizedStringForValue(NavBarTitle.Home)
static func localizedStringForValue<T: Localizeable>(localizeableValue: T) -> String {
return NSLocalizedString(localizeableValue.localizedString, comment: localizeableValue.localizedStringComment)
}
}
protocol Localizeable {
var localizedStringComment: String { get }
var localizedString: String { get }
}
enum NavBarTitle: Localizeable {
case Home, NewOffer, Search
var localizedStringComment: String {
get {
switch self {
case .Home:
return "Navigation bar home title"
case .NewOffer:
return "Some comment"
case .Search:
return "Some comment"
}
}
}
var localizedString: String {
get {
switch self {
case .Home:
return "navbar.home.title"
case .NewOffer:
return "navbar.newoffer.title"
case .Search:
return "navbar.search.title"
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment