0

Writing one line code using the ternary operator:

let rawValue: String = ...
let subtype: String? = ...
let display = subtype != nil ? "\(rawValue) (\(subtype))" : rawValue

The compiler complains: String interpolation produces a debug description for an optional value; did you mean to make this explicit?

Add ! to force unwrapping subtype in the string interpolation:

let display = subtype != nil ? "\(rawValue) (\(subtype!))" : rawValue

Now SwiftLint complains: Force Unwrapping Violation: Force unwrapping should be avoided. (force_unwrapping)

How to rewrite this one line code?

Xaree Lee
  • 3,188
  • 3
  • 34
  • 55

1 Answers1

3

I would map the optional to the interpolated string, and use ?? to provide the default value:

let display = subtype.map { "\(rawValue) (\($0))" } ?? rawValue
Sweeper
  • 213,210
  • 22
  • 193
  • 313