Last active
April 17, 2021 09:56
-
-
Save yutailang0119/d8da0e7c9ceacadafa83435efa00ed6b to your computer and use it in GitHub Desktop.
Localized Text for SwiftUI
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 | |
import SwiftUI | |
protocol TextLocalizable { | |
var `default`: String { get } | |
var enUS: String { get } | |
var jaJP: String { get } | |
// TODO: Implement others of Locale.availableIdentifiers | |
} | |
extension TextLocalizable { | |
var enUS: String { | |
`default` | |
} | |
var jaJP: String { | |
`default` | |
} | |
} | |
struct LocalizedText<T: TextLocalizable>: View { | |
@Environment(\.locale) private var locale | |
private let t: T | |
init(_ t: T) { | |
self.t = t | |
} | |
var body: some View { | |
switch locale.identifier { | |
case "en_US": | |
Text(verbatim: t.enUS) | |
case "ja_JP": | |
Text(verbatim: t.jaJP) | |
default: | |
Text(verbatim: t.default) | |
} | |
} | |
} | |
struct ContentView: View { | |
enum LocalizedTextValue: TextLocalizable { | |
case hello | |
case name(String) | |
var `default`: String { | |
enUS | |
} | |
var enUS: String { | |
switch self { | |
case .hello: | |
return "Hello" | |
case .name(let name): | |
return "\(name)-san" | |
} | |
} | |
var jaJP: String { | |
switch self { | |
case .hello: | |
return "こんにちは" | |
case .name(let name): | |
return "\(name)さん" | |
} | |
} | |
} | |
var body: some View { | |
VStack { | |
LocalizedText(LocalizedTextValue.hello) | |
LocalizedText(LocalizedTextValue.name("yutailang0119")) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment