使用可变参数格式化字符串 [英] Format string with variadic arguments
问题描述
我有String扩展名
I have extension for String
func localized(table: String? = nil, bundle: Bundle = .main, args: CVarArg...) -> String {
return String(
format: NSLocalizedString(
self,
tableName: table,
bundle: bundle,
value: self,
comment: ""
),
args
)
}
Localizable.strings文件:
Localizable.strings file:
"%d seconds ago" = "%d seconds ago";
用法:
print("%d seconds ago".localized(args: 5))
print(String.localizedStringWithFormat("%d seconds ago", 5))
结果:
<some_random_number_here> seconds ago.
5 seconds ago.
有人可以向我解释我该怎么做吗?
Can someone explain me what do I do wrong?
推荐答案
String
具有两个类似的初始化程序:
String
has two similar initializers:
init(format: String, _ arguments: CVarArg...)
init(format: String, arguments: [CVarArg])
第一个使用不同数量的参数,第二个使用 具有所有参数的数组:
The first one takes a varying number of arguments, the second one an array with all arguments:
print(String(format: "x=%d, y=%d", 1, 2))
print(String(format: "x=%d, y=%d", arguments: [1, 2]))
在您的localized
方法中,args: CVarArg...
是可变参数
并且这些在函数体内以 array 的形式提供
的类型,在这种情况下为[CVarArg]
.
因此,必须将其传递给String(format: arguments:)
:
In your localized
method, args: CVarArg...
is a variadic parameter
and those are made available within the functions body as an array
of the appropriated type, in this case [CVarArg]
.
Therefore it must be passed to String(format: arguments:)
:
func localized(table: String? = nil, bundle: Bundle = .main, args: CVarArg...) -> String {
return String(
format: NSLocalizedString(
self,
tableName: table,
bundle: bundle,
value: self,
comment: ""
),
arguments: args // <--- HERE
)
}
另请参见函数中的"可变参数"" 快速参考.
这篇关于使用可变参数格式化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!