Last active
March 4, 2016 02:35
-
-
Save rhysforyou/db62551a84fd37b7868f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // | |
| // Localization.swift | |
| // Pokedex | |
| // | |
| // Created by Rhys Powell on 3/03/2016. | |
| // Copyright © 2016 Rhys Powell. All rights reserved. | |
| // | |
| import Foundation | |
| import RealmSwift | |
| public class LocalizationHelper { | |
| static func preferredLanguages() -> [String] { | |
| var languages = NSLocale.preferredLanguages() | |
| .map { language in | |
| return language.componentsSeparatedByString("-").first ?? language | |
| } | |
| languages.append("en") | |
| return languages | |
| } | |
| static func predicateForLanguage(language: String) -> NSPredicate { | |
| return NSPredicate(format: "language.iso639 = %@", language) | |
| } | |
| } | |
| public protocol Localizable { | |
| var language: Language! { get } | |
| } | |
| public extension RealmCollectionType where Element : Localizable { | |
| func objectForLanguage(language: String) -> Element? { | |
| return self | |
| .filter(LocalizationHelper.predicateForLanguage(language)) | |
| .first | |
| } | |
| var objectForCurrentLocale: Element? { | |
| return LocalizationHelper.preferredLanguages() | |
| .flatMap(objectForLanguage) | |
| .first | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment