iJKTen
(JK)
1
I am trying to build a JSON parser as an exercise and I was thinking what if I have an enum called Token with values like
enum Token: String {
case OpenCurly = "{"
case CloseCurly = "}"
case OpenArray = "["
case CloseArray = "]"
case Comma = ","
case Colon = ":"
case String(String)
case Number
case Boolean
case Null
}
here OpenCurly can only be "{" but a string can be anything. But I guess I cannot have associated values and raw values together? If there a way for an associated value to be a certain string or am going about this the wrong way?
1 Like
Pippin
(Ethan Pippin)
2
When setting the raw type like that the compiler will automatically synthesize the RawRepresentable conformance. When used this way, it can't derive a raw value when an associated value is present. You will have to make your own RawRepresentable comformance:
enum Token: RawRepresentable {
case OpenCurly
case CloseCurly
case OpenArray
case CloseArray
case Comma
case Colon
case String(String)
case Number
case Boolean
case Null
init?(rawValue: String) {
switch rawValue {
case "{":
self = .OpenCurly
// other values
default:
self = .String(rawValue)
}
}
var rawValue: String {
switch self {
case .OpenCurly:
"{"
case .String(let value):
value
// other values
}
}
}
3 Likes
iJKTen
(JK)
3
ah got it. I think will not use raw values here but only use associated data for some cases where it makes sense.
Thank you!