Skip to content

Instantly share code, notes, and snippets.

@dodikk
Forked from tapoton/Localized.swift
Created May 5, 2017 09:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dodikk/ec5207a30b49b9912da7e6ecfe03339c to your computer and use it in GitHub Desktop.
Save dodikk/ec5207a30b49b9912da7e6ecfe03339c to your computer and use it in GitHub Desktop.
Strongly typed localization for domain grouped strings.
import Foundation
protocol Domain {
associatedtype Parent = Domain
static var name: String { get }
static var fullName: String { get }
}
extension Domain {
static var name: String {
return "\(self)"
}
static var fullName: String {
return name
}
}
extension Domain where Parent: Domain {
static var fullName: String {
return "\(Parent.fullName).\(name)"
}
}
protocol LocalizationKey {
var key: String { get }
var keyPath: String { get }
}
extension LocalizationKey {
var key: String {
return "\(self)"
}
var keyPath: String {
return key
}
func string(comment: String = "") -> String {
return NSLocalizedString(self.keyPath, comment: comment)
}
}
extension LocalizationKey where Self: Domain {
var keyPath: String {
return "\(type(of: self).fullName).\(key)"
}
}
// MARK: Example
enum Localized {
enum Friends: Domain {
typealias Parent = Localized
enum All: String, Domain, LocalizationKey {
typealias Parent = Friends
case title = "Title"
case message = "Message"
var key: String {
return self.rawValue
}
}
}
}
let title = Localized.Friends.All.title.string()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment