-
-
Save dodikk/ec5207a30b49b9912da7e6ecfe03339c to your computer and use it in GitHub Desktop.
Strongly typed localization for domain grouped strings.
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
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