Swift 自定义字符串格式扩展始终返回 0
我需要自定义字符串格式扩展,但我有一些字符串格式问题。
这是代码。
print(String(format: "%.1f", 1.12))
print(String.format("%.1f", 1.12))
extension String {
static func format(_ format: String, _ arguments: CVarArg...) -> String {
return String(format: format, arguments)
}
}
输出
1.1
0.0
为什么输出不一样?谢谢!
I need my custom string format extension but I have some string format problem.
Here's code.
print(String(format: "%.1f", 1.12))
print(String.format("%.1f", 1.12))
extension String {
static func format(_ format: String, _ arguments: CVarArg...) -> String {
return String(format: format, arguments)
}
}
output
1.1
0.0
Why the outputs not the same? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为发生这种情况是因为扩展中格式函数的返回类型是
(_ format: String, _ argument: CVarArg...)
。 return 必须是String(format: String, Arguments:[CVarArg])
。函数中的参数arguments
是[CVarArg]
的类型,并且如果您在返回字符串格式类型中使用_arguments: CVarArg...
而不是[CVarArg]
,arguments
的参数将是[[CVarArg]]
。现在它实际上是二维数组。可能会因此而失败。这也行不通
I think it happens because return type of the format function in extension is
(_ format: String, _ arguments: CVarArg...)
. return must beString(format: String, arguments:[CVarArg])
.Parameterarguments
in function is type of[CVarArg]
and If you use_ arguments: CVarArg...
instead of[CVarArg]
in return String format type , the parameter of thearguments
gonna be[[CVarArg]]
. It is actually 2d array right now . It may fail because of this.Also this is not works too