0

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?

6
  • Note that your Objective-C version does not compute the values in the format string itself. The format is fixed and the argument computes the string. Commented Aug 12, 2018 at 9:31
  • @MartinR That's correct, but in Swift I could compute values, such as '\(sampleRate/1000)' in format string itself. Commented Aug 12, 2018 at 9:32
  • 1
    Perhaps you mean string interpolation: let s = "Audio: \(numChannels > 1 ? "Stereo" : "Mono")" Commented Aug 12, 2018 at 9:33
  • 1
    The reason that your Swift code does not compile is the missing spaces around ? and : Commented Aug 12, 2018 at 9:35
  • 1
    You can even compose the string without String(format and without String Interpolation: "Audio :" + (numChannels > 1 ? "Stereo" : "Mono") Commented Aug 12, 2018 at 11:47

2 Answers 2

2

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")"
Sign up to request clarification or add additional context in comments.

Comments

1

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

6 Comments

It should be %@ for a Swift string.
Yeah, I realised that
@DeepakSharma, the %@ legacy from Objective-C is because String(format:) is not pure Swift but comes by way of the Foundation framework. Note that you have to import Foundation (or UIKit or AppKit or Cocoa) to use it. So "Stereo" and "Mono" get passed as NSString.
Why was this downvoted? It works as expected and is one of several valid solutions.
Code only answers are improved with some explanation
|

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.