The SwiftLocaleKit is libriry for simlify localization and synchronize it with system localization settings and synchronize them.
SwiftLocaleKit is available with Swift Package Manager.
The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler.
Once you have your Swift package set up, adding SwiftLocaleKit as a dependency is as easy as adding it to the dependencies value of your Package.swift.
dependencies: [
.package(url: "https://github.com/FuturraGroup/SwiftLocaleKit.git", from: "1.6.0")
]First of all - imoprt SwiftLocaleKit
import SwiftLocaleKit
let localized = "My Awesome string".localizedYou don't need special setups for using SwiftLocaleKit.
After first call singleton of LocaleKit it'll setup automaticaly laguage pased by system as default.
By default the seed language is taken from the system's preferred languages list. If the user's
first preferred language is not one your app actually localizes, you can provide a fallback that is
used instead. Call configure(defaultLanguage:) as early as possible — for example at the very
start of application(_:didFinishLaunchingWithOptions:) — and before the first access to
LocaleKit.shared:
import SwiftLocaleKit
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
LocaleKit.configure(defaultLanguage: LocaleKitLanguage(code: "en"))
return true
}If the first preferred language is supported by your app it always wins; the default is only used when no supported preferred language is available.
For example, getting current language information will setup all basic stuff:
let language = LocaleKit.shared.currentLanguageand calling localization will do the same:
let localized = "My Awesome string".localizedThere is 3 ways to localize your strings with SwiftLocaleKit:
Example 1 how to get localized string.
This is simlified version of NSLocalizedString
In this case key it's your string you calling on this variable property.
let localized = "My Awesome string".localizedExample 2 how to get localized string.
This version based on NSLocalizedString. Accepts all NSLocalizedString parameters except bundle and key
In this case key it's your string you calling on this method.
let localized = "My Awesome string".localized(comment: "My locale string")Example 3 how to get localized string.
This method works like localized property from LocaleKit, but using custom language you passed to localize.
In this case key it's your string you calling on this method.
You can path any custom LocaleKitLanguage to this method.
let localized = "My Awesome string".localized(LocaleKit.shared.currentLanguage)You can change localization of your app in runtime. All you need - implement reload localized UI in change locale completion.
let selectedLanguage = LocaleKit.shared.sortedLanguages[indexPath.row]
/// Set new localization language.
/// Handle locale changes and reload UI in completion
LocaleKit.shared.setLocale(selectedLanguage) { [weak self] in
/// Start UI reload after language select.
/// In our example will use local `Notificatication`
NotificationCenter.default.post(name: Notification.Name(rawValue: "App.reloadLocaleNotification"), object: nil)
DispatchQueue.main.async { [weak self] in
self?.navigationController?.popViewController(animated: true)
}
}
...
NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: "App.reloadLocaleNotification"), object: nil, queue: OperationQueue.main) { [weak self] _ in
translatedText1Label.text = "My Awesome string".localized
}Also, SwiftLocaleKit provides some aditional features:
currentLanguage - property of LocaleKit singleton that represents default/current selected language.
preferedLanguages - property of LocaleKit singleton that represents preferredLanguages list as array of LocaleKitLanguage.
allSupportedLanguages - property of LocaleKit singleton that represents all supported to localizeteon implemented in your app. Also array of LocaleKitLanguage.
sortedLanguages - Sorted languages list in order: first preferedLanguages, than allSupportedLanguages with excluded languages from preferedLanguages. Also array of LocaleKitLanguage.
selectedAppLocale - The app's effective selected language: currentLanguage when it is among allSupportedLanguages, otherwise the closest supported match (by shortCode), finally falling back to English. Handy for sending the active language to a backend or resolving a supported language for UI.
isRTL - true when the selected language is written right-to-left. Drives layout direction from the in-app selected language (not the system language).
appSemanticContentAttribute / appLayoutDirection (UIKit) - the UISemanticContentAttribute / UIUserInterfaceLayoutDirection implied by the selected language. Push appSemanticContentAttribute onto the appearance proxy / windows to flip the whole UI for RTL languages.
LocaleKitLanguage - sctrucrure used by LocaleKit to represent any language and localize your app. Can be inited with any language code
let language = LocaleKitLanguage(code: "en")
let languageZhHans = LocaleKitLanguage(code: "zh-Hans")Has properties:
code - language code inited with.
shortCode - short version of code that drops regoin or/and transcription. For example, if you init:
let languageZhHans = LocaleKitLanguage(code: "zh-Hans")short code will be:
print(languageZhHans.shortCode) // Print output: "zh"locale - [Locale](https://developer.apple.com/documentation/foundation/locale) object based on provided language code
nativeName - Localized language name on this language.
deviceLocaleName - Localized language name on language provided by system. System language can be different from SwiftLocaleKit if you change locale in SwiftLocaleKit
currentLocaleName - Localized language name on currentLanguage from SwiftLocaleKit
characterDirection - Text/character direction (Locale.LanguageDirection) of this language. Unknown directions default to .leftToRight.
Two LocaleKitLanguage values are considered equal (==) when they share the same full code or the same shortCode (e.g. en == en-US, ar == ar-EG). This matches the broader "same language" comparison apps usually need when matching a profile/device language against the supported localizations.
Contributions for improvements are welcomed. Feel free to submit a pull request to help grow the library. If you have any questions, feature suggestions, or bug reports, please send them to Issues.
MIT License
Copyright (c) 2023 Futurra Group
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.