swift : use of %s in String(format: ...)

Viewed 24342

I would like to format a string with another string like this:

var str = "Hello, playground"
print (String(format: "greetings %s", str))

This leads to this beautiful result:

greetings 哰૧

I tried with %@ and it works but, as I'm getting format string from another programming language, I would like, if possible to use the %s tag. Is there a way to ?

1 Answers

Solution 1: changing the format

If the format is from a reliable external source, you can convert it to replace occurences of %s with %@:

So, instead of:

String(format: "greetings %s", str)

You do:

String(format: "greetings %s".replacingOccurrences(of: "%s", with: "%@"), str)

Solution 2: changing the string

If the format is complex, a simple replacement won't work. For instance:

  • when using a specifier with a numeric character sequence: %1$s
  • when using the '%' character followed by an 's': %%s
  • when using a width modifier: %-10s

In similar cases, we need to stick to a C string.

So instead of:

String(format: "greetings %s", str)

You do:

str.withCString {
    String(format: "greetings %s", $0)
}
Related