Last active
July 20, 2019 22:28
-
-
Save rsaenzi/8bf425753a7c7349a811914aa532b475 to your computer and use it in GitHub Desktop.
To manage strings localization using the default localization system: Localizable.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
// | |
// Language.swift | |
// | |
// Created by Rigoberto Sáenz Imbacuán (https://www.linkedin.com/in/rsaenzi/) | |
// Copyright © 2017. All rights reserved. | |
// | |
// Dependencies: | |
// - Language+UIKit: https://gist.github.com/rsaenzi/a575e66f5e617559767e5b523bad2161 | |
import Foundation | |
class Language { | |
/** | |
This function will return the localized text specified by its key | |
*/ | |
static func get(_ key: LanguageKey, from bundle: Bundle = .main) -> String { | |
return NSLocalizedString(key.rawValue, tableName: nil, bundle: bundle, value: "", comment: "") | |
} | |
/** | |
This function will replace any ocurrence of $0$, $1$, $2$, $3$ ... $X$ | |
on the localized text, for the specified values | |
*/ | |
static func get(_ key: LanguageKey, replacing values: [String], from bundle: Bundle = .main) -> String { | |
var text = NSLocalizedString(key.rawValue, tableName: nil, bundle: bundle, value: "", comment: "") | |
guard values.count > 0 else { | |
return text | |
} | |
for index in 0..<values.count { | |
text = text.replacingOccurrences(of: "$\(index)$", with: values[index]) | |
} | |
return text | |
} | |
/** | |
This function will replace any ocurrence of $0$, $1$, $2$, $3$ ... $X$ | |
on the main localized text, for the localized strings specified by its keys | |
*/ | |
static func get(_ key: LanguageKey, replacing keys: [LanguageKey], from bundle: Bundle = .main) -> String { | |
let values = keys.map { parameterKey -> String in | |
return get(parameterKey) | |
} | |
return Language.get(key, replacing: values, from: bundle) | |
} | |
} | |
// Should be in a different swift file | |
enum LanguageKey: String { | |
case appName | |
case OK | |
case Cancel | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment