Skip to content

Instantly share code, notes, and snippets.

@jancassio
Created April 15, 2021 23:53
Show Gist options
  • Save jancassio/7b0d8f3407bad447c6aed74ab09e2a08 to your computer and use it in GitHub Desktop.
Save jancassio/7b0d8f3407bad447c6aed74ab09e2a08 to your computer and use it in GitHub Desktop.
Localizable String Extensions
//
// String+Localized.swift
//
// Created by Jan Cássio on 2021/03/27.
// Copyright © 2021 Jan Cassio. All rights reserved.
//
import Foundation
extension String {
/**
# Localized
Return a localized text for a given string.
### Example:
```
"key_for_a_localized_string".localized() // return the localized string for given string.
```
- Parameters:
- in: The Bundle where the Localizable.strings are, default is .main.
- value: Used as fallback value. Default is `""`
- comment: An addition string to describe the text. Default is `""`.
- Returns:
the localized string, otherwise returns the string assigned to `value` parameter.
*/
func localized(in bundle: Bundle = .main, value: String = "", comment: String = "") -> String {
return NSLocalizedString(
self,
bundle: bundle,
value: value,
comment: comment
)
}
}
/**
# StringLocalizable Protocol
StringLocalizable enable to some type to use any enumerator of string as a source of strong typed localized strings.
In the example below, each case in `Localized Keys` is a key for a localized string hosted in the main bundle.
```
enum LocalizedKeys: String {
case title
case subtitle
}
extension MyView {
typealias Options = LocalizedKeys
func localized(_ key: Options) -> String {
return key.rawValue.localized()
}
}
// anywhere in the MyView, you could obtain localized string just doing this:
let title = localized(.title) // string for "title" key
let subitle = localized(.subtitle) // string for "title" key
*/
protocol StringLocalizable {
/** Options could be any Enum raw representable by `String` type. */
associatedtype Options: RawRepresentable where Options.RawValue == String
/**
# Localized
Get the localized string from the given Option
- Returns:
A localized string or a empty string if the key was not found.
*/
func localized(_ key: Options) -> String
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment