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!
CodePudding user response:
I think it happens because return type of the format function in extension is (_ format: String, _ arguments: CVarArg...)
. return must be String(format: String, arguments:[CVarArg])
.Parameter arguments
in function is type of [CVarArg]
and If you use _ arguments: CVarArg...
instead of [CVarArg]
in return String format type , the parameter of the arguments
gonna be [[CVarArg]]
. It is actually 2d array right now . It may fail because of this.
Also this is not works too
print(String(format: "%.1f", [1.12])) // args is CVarArg...