1

Suppose that I have a String object in Swift and I want to use String format class method to combine it and several other objects like this:

var foo = 0
var str = "str"
String(format: "%d (%s)", foo, str)

This example doesn't work as expected because %s can't handle String objects. How can I do it then?

Thanks in advance.

3 Answers 3

3

String(format:) is bridged to the -[NSString initWithFormat] method and accepts the same format specifiers, such as %@ for objects. String is bridged to NSString automatically, therefore you can use %@ for Swift strings as well. Also note that the Swift Int type corresponds to long in C:

var foo = 0
var str = "str"
let result = String(format: "%ld (%@)", foo, str)
Sign up to request clarification or add additional context in comments.

Comments

1

you just use string interpolation

var foo = 0
var str = "str"
String(format: "%d (\(str))", foo)

1 Comment

This will crash if the string contains anything that would be interpreted as a format, e.g. with str = "str%d".
0

Unless there's a reason you need the Foundation method for String creation, you can use "string interpolation". For instance:

let str = "I am \(height.feet) feet \(height.inches) inches tall."

Produces: "I am 6 feet 5 inches tall." Using string interpolation you can insert your variables inline and not have to mess with C-esque placeholders in a format statement.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.