Why does Xcode tell me to add .map {$ 0.rawValue} when I can just do? .RawValue?

I have this code:

enum Enum: String { case A = "A" } let s: String? = Enum(rawValue: "A") 

Of course, it does not compile. I usually fix this as follows:

 let s: String? = Enum(rawValue: "A")?.rawValue 

However, Xcode says I should add .map { $0.rawValue } :

enter image description here

This is strange because it is clear that Xcode knows that accessing rawValue can turn Enum into a String . But why does he suggest doing this with map ? Why not just access it directly?

I thought Xcode would think like this:

I have a string constant on the left and an enumeration whose original value is a string. Types are incompatible, but I know that rawValue can turn an enumeration into a string. I just suggest the user add ?.rawValue !

What is the "thinking process" of Xcode?

PS My intention here is to check if "A" valid source value for enumeration. If so, assign it s , otherwise assign nil . I know this is not very practical, but I'm just interested in the behavior of Xcode.

+6
source share
2 answers

Joao Marcelo Souzy's third answer is exactly correct. .map is an optional method of securely deploying par excellence. Enum(rawValue: "A").map{$0.rawValue} - Enum(rawValue: "A")?.rawValue .

The only problem is that we are all so used to using the second (syntactic sugar) that we forget that the first of them, as Swift thinks, is under the hood.

Example:

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

This does not apply 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'm not sure why Xcode assumes that instead of just .rawValue , but I can think of several possible reasons:

  • Alphabet order.
  • You can perform some operation on the expanded value.
  • Perhaps foo?.bar is just syntactic sugar for foo.map { $0.bar }
+2
source

Source: https://habr.com/ru/post/1015531/


All Articles