Swift String format vs Objective-C

147 Views Asked by At

I am using swift String(format:...) and need to compute values in the format string itself using ternary operator, something like this but it doesn't compiles.

 String(format: "Audio: \(numChannels>1?"Stereo": "Mono")")

In Objective-C, I could do like this:

 [NSString stringWithFormat:@"Audio: %@",  numChannels > 1 ? @"Stereo" : @"Mono"];

How do I achieve the same elegance in Swift without having an intermediate variable?

2

There are 2 best solutions below

0
Martin R On BEST ANSWER

Due to the missing spaces around the operators in the conditional expression, the compiler misinterprets 1?"Stereo" as optional chaining. It should be

String(format: "Audio: \(numChannels>1 ? "Stereo" : "Mono")")

instead. However, since the format string has no placeholders at all, this is equivalent to

"Audio: \(numChannels > 1 ? "Stereo" : "Mono")"
6
Joakim Danielson On

One option is to use String(format:) with a placeholder and the conditional expression as the parameter for the placeholder

String(format: "Audio = %@", numChannels > 1 ? "Stereo" : "Mono")