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?
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")"