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 }
:
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.
source share