[swift-users] Codable Range in Xcode 9 playground

Thierry Passeron thierry.passeron at gmail.com
Tue Oct 17 11:59:58 CDT 2017


Hi everyone,

In the process of familiarising myself with Encodable/Decodable protocols I was trying to apply it to the Range struct in order to persist a Range in CoreData records. However, I seem to hit the wall with it and keep getting errors. This happens in the Xcode 9.0.1 playground, not sure which swift version is used if it’s 4 or 3.x but anyways, I get “Ambiguous reference to member ‘encode(_:forKey:)’ on every encode/decode method calls.

extension Range {
  enum CodingKeys : String, CodingKey {
    case upperBound
    case lowerBound
  }
}

extension Range: Codable {
  
  public func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encode(upperBound, forKey: .upperBound)
    try container.encode(lowerBound, forKey: .lowerBound)
  }
  
  public init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    self.upperBound = try values.decode(Bound.self, forKey: .upperBound)
    self.lowerBound = try values.decode(Bound.self, forKey: .lowerBound)
  }

}

How would one add Codable support to such a struct? I’m feeling it may require a bit of “where” clauses in extension because of the Generic aspect of this struct but I fail to make the compiler happy.

Any help appreciated.

Best regards,
Thierry




More information about the swift-users mailing list