Question about generic CasePath value #61
-
I'm playing around with following code: struct FooState {}
struct BarState {}
struct BazState {}
enum State {
case foo(FooState), bar(BarState), baz(BazState)
}
enum StateType: String {
case foo, bar, baz
}
extension StateType {
func decodeType<V>() -> CasePath<State, V> {
switch self {
case .foo: return (/State.foo)
case .bar: return (/State.bar)
case .baz: return (/State.baz)
}
}
} But getting an error GenericCasePathValue-Xcode-13.2.zip Updating extension StateType {
func decodeType<V>() -> CasePath<State, V> {
switch self {
case .foo:
let a = /State.foo
return a
case .bar:
let a = /State.bar
return a
case .baz:
let a = /State.baz
return a
}
}
} Produces |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
How do you plan on using |
Beta Was this translation helpful? Give feedback.
-
Turns out I was trying to over-engineer a bit. CasePaths nor Swift generics are needed for this to work: public enum State: Decodable {
case foo(FooState), bar(BarState), baz(BazState)
enum `Type`: String, Decodable {
case foo, bar, baz
enum CodingKeys: CodingKey {
case type
}
}
public init(from decoder: Decoder) throws {
let typeContainer = try decoder.container(keyedBy: `Type`.CodingKeys.self)
let type = try typeContainer.decode(`Type`.self, forKey: .type)
switch type {
case .foo: self = .foo(try FooState(from: decoder))
case .bar: self = .bar(try BarState(from: decoder))
case .baz: self = .baz(try BazState(from: decoder))
}
}
}
let data = "{ \"type\": \"foo\" }".data(using: .utf8)!
let state = try! JSONDecoder().decode(State.self, from: data) Thanks @iampatbrown for the rubber ducking! 🦆 |
Beta Was this translation helpful? Give feedback.
Turns out I was trying to over-engineer a bit. CasePaths nor Swift generics are needed for this to work: