Skip to content

Question about generic CasePath value #61

Answered by ferologics
ferologics asked this question in Q&A
Discussion options

You must be logged in to vote

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))
    }
  }
}

Replies: 2 comments 4 replies

Comment options

You must be logged in to vote
4 replies
@ferologics
Comment options

@ferologics
Comment options

@iampatbrown
Comment options

@ferologics
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by ferologics
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants