-4

If case in one line, is it possible?

Example:

@Environment(\.colorScheme) var colorScheme

let str = if case .dark == colorScheme ? "dark" : "light"

Think question similar to this

Neph Muw
  • 780
  • 7
  • 10

1 Answers1

1

case + = is just a different spelling enabled by having ~= defined.

if case 1... = 2 // true! 
if 1... ~= 2 // Same as above.

So, you could write

let str = .dark ~= colorScheme ? "dark" : "light"

But all that does is call ==

public func ~= <T: Equatable>(a: T, b: T) -> Bool {
  return a == b
}

…so you should just write it more clearly, as suggested by the comments:

let str = colorScheme == .dark ? "dark" : "light"

Also, never name anything str. That practice is a holdover from a time when variable name length mattered.