Group Group Group Group Group Group Group Group Group

%@ vs \(variable)

#1

On page 79 of the 4th iOS tutorial, Matthijs uses %@ instead of (stringInterpolation). Why? I’ve tried it out both ways and it seems to work and using string interpolation seems much clearer. Are they just two different ways of doing the same thing?

cell.artistNameLabel.text = String(format: “%@ (%@)”, searchResult.artistName, searchResult.kind)

VS

cell.artistNameLabel.text = “(searchResult.artistName) ((searchResult.kind))”

Edit: The backslashes before the string interpolation don’t seem to be appearing in the text above.

#2

@gogreen37 Thanks very much for your question, and my apologies for the delayed response.

I honestly don’t see much of a difference between the two approaches, except that I can see someone who is used to doing things from an Objective-C background would prefer using the %@ approach, whereas the “Swifty” approach would be to use String Interpolation.

The one thing I will say is that %@ EXPECTS a String object (as opposed to a primitive like int), whereas () will cast WHATEVER is inside the brackets into a String. Sort of a “one size fits all” solution. :slight_smile: So to answer your question here, I would say the %@ approach is perhaps being used to ensure that ONLY a String object is displayed, and nothing else, whereas () would be used as a convenience method which could be applied when one does not have to worry about the type that is going to be displayed.

Neither is wrong, both are legitimate syntax to use. It’s really a matter of preference. The only thing I would say to any developer is, whichever approach you use, be consistent in using that approach throughout your project.

I hope this helps!

All the best!

#3

@gogreen37,
Nice question, there is one more fact that makes a bit of a difference - Optionals.

take this code for example

let str:String? = "Hello"
print(str).           // Optional("Hello")

print("\(str)")     // Optional("Hello")

print(String(format:"%@", str))

you will find that first format requires the value to be non nil, so you will have to either add a ! or ?? "" to the line.

Secondly, as @syedfa also mentioned, you can quickly build a mixed output mixing strings and ints and doubles etc without doing much. Basically print tries to use the description method (if it is implemented for a struct or class and if it conforms to the customStringConvertible or customDebugStringConvertible

cheers,

Jayant