Search code examples
swiftstring-formatting

Swift custom string format extension always return 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!


Solution

  • 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 argumentsin 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...