Why is Xcode telling me to add .map { $0.rawValue } when I can just do ?.rawValue? Why is Xcode telling me to add .map { $0.rawValue } when I can just do ?.rawValue? xcode xcode

Why is Xcode telling me to add .map { $0.rawValue } when I can just do ?.rawValue?


João Marcelo Souza's third answer is exactly correct. .map is the Optional safe-unwrapping method par excellence. Enum(rawValue: "A").map{$0.rawValue} is Enum(rawValue: "A")?.rawValue.

The problem is merely that we are all so used to using the second one (syntactic sugar) that we forget that the first one is how the Swift compiler actually thinks, under the hood.

Example:

var i : [Int]? = [7]i.map {$0.count} // 1i?.count // 1i = nili.map {$0.count} // nili?.count // nil


It's not specific to Enum. In fact, all Optional instances implement the map function:

let possibleNumber: Int? = Int("4")let possibleSquare = possibleNumber.map { $0 * $0 }print(possibleSquare) // Prints "Optional(16)"

I am not sure why Xcode suggests that instead of just .rawValue but I can think of a few possible reasons:

  1. Alphabetical order.
  2. You may want to perform some operation on the unwrapped value.
  3. Maybe foo?.bar is just syntax sugar for foo.map { $0.bar }