有没有办法让苹果的genstrings命令行工具识别从SwiftUI的LocalizedStringKey初始化器中定义的可本地化的字符串键?
对于此输入文件(testing-genstrings.swift):...
import UIKit
import SwiftUI
enum L10n {
static let test0 = NSLocalizedString("TEST0", comment: "")
static let test1 = LocalizedStringKey("TEST1")
static func test2(_ parameter: String) -> LocalizedStringKey {
return LocalizedStringKey("TEST2_\(parameter)")
}
static func test3(_ parameter: String) -> String {
return NSLocalizedString("TEST3_\(parameter)", comment: "")
}
static func test4(_ parameter: String) -> String {
return String.localizedStringWithFormat(NSLocalizedString("TEST4", comment: ""), parameter)
}
}
let test5 = "TEST5"
let test6 = "TEST6"
let test7 = "TEST7"
struct TestView: View {
var body: some View {
VStack {
Text(L10n.test0)
Text(L10n.test1)
Text(L10n.test2("foo"))
Text(L10n.test3("bar"))
Text(test5)
Text(LocalizedStringKey(test6))
Text(NSLocalizedString(test7, ""))
Text("TEST8")
Text("TEST9_\("baz")")
}
}
}...genstrings生成以下输出:
$ genstrings -SwiftUI -s LocalizedStringKey testing-genstrings.swift && iconv -c -f utf-16 -t utf-8 Localizable.strings
genstrings: error: bad entry in file testing-genstrings.swift (line = 9): Argument is not a literal string.
genstrings: error: bad entry in file testing-genstrings.swift (line = 11): Argument is not a literal string.
genstrings: error: bad entry in file testing-genstrings.swift (line = 12): Argument is not a literal string.
genstrings: error: bad entry in file testing-genstrings.swift (line = 36): Argument is not a literal string.
genstrings: error: bad entry in file testing-genstrings.swift (line = 37): Argument is not a literal string.
genstrings: error: bad entry in file testing-genstrings.swift (line = 37): Argument is not a literal string.
/* No comment provided by engineer. */
"bar" = "bar";
/* No comment provided by engineer. */
"foo" = "foo";
/* No comment provided by engineer. */
"TEST0" = "TEST0";
/* No comment provided by engineer. */
"TEST3_\(parameter)" = "TEST3_\(parameter)";
/* No comment provided by engineer. */
"TEST4" = "TEST4";
/* No comment provided by engineer. */
"TEST8" = "TEST8";
/* No comment provided by engineer. */
"TEST9_%@" = "TEST9_%@";您可以看到,它可以识别通过NSLocalizedString和Text的初始化器Text()定义的键,该初始化器使用ExpressibleByStringInterpolation (在本例中为TEST9_%@),但无法识别使用LocalizedStringKey定义的所有键。
发布于 2021-02-03 09:26:33
genstrings相对幼稚。它正在寻找一个具有两个参数的函数,第一个参数未命名,第二个参数命名为"comment“。
如果添加了以下扩展名:
public extension LocalizedStringKey {
init(_ value: String, comment: String) {
self.init(value)
}
}你可以通过将-s LocalizedStringKey传递给genstrings来使用LocalizedStringKey。
请记住,如果将LocalizedStringKey声明为返回类型或变量,也会产生genstrings错误。因此,您需要一个单独的typealias LocalizedStringKeyResult = LocalizedStringKey,以便在引用LocalizedStringKey时使用,但又不希望genstrings抱怨。
当然,你不会得到你想要的插值,因为genstrings只应用于Text。
真正的答案是...不要使用LocalizedStringKey。尽可能使用Text (以获得插值)。如果不能使用NSLocalizedString,请使用它。
https://stackoverflow.com/questions/62300515
复制相似问题