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
  • 2,876
  • 3
  • 28
  • 51

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
  • 176,635
  • 17
  • 154
  • 256