swiftargo

How can I create subclasses using Argo and Swift?


I'm using Argo in a Swift app to decode JSON into objects. I have JSON like this:

"activities": [
  {
    "id": "intro-to-the-program",
    "type": "session",
    "audio": "intro-to-the-program.mp3"
  },
  {
    "id": "goal-setting",
    "type": "session",
    "audio": "goal-setting.mp3"
  },
  {
    "id": "onboarding-quiz",
    "type": "quiz"
  }
]

Based on the 'type', I actually want to instantiate a subclass of the Activity class (ActivitySession, ActivityQuiz etc) and have the subclass do its own decoding.

How can I do this? The top-level decode() function expects a return type of Decoded<Activity>, and none of my approaches so far seem able to defeat it.


Solution

  • Here's one way you can do this by switching on the type to conditionally decode it and get a nice error message when an invalid type is given.

    struct ThingWithActivities: Decodable {
      let activities: [Activity]
    
      static func decode(json: JSON) -> Decoded<ThingWithActivities> {
        return curry(ThingWithActivities.init)
          <^> json <|| "activities"
      }
    }
    
    class Activity: Decodable {
      let id: String
    
      init(id: String) {
        self.id = id
      }
    
      class func decode(json: JSON) -> Decoded<Activity> {
        let decodedType: Decoded<String> = json <| "type"
        return decodedType.flatMap { type in
          switch type {
            case "session": return ActivitySession.decode(json)
            case "quiz": return ActivityQuiz.decode(json)
          default:
            return .Failure(.Custom("Expected valid type, found: \(type)"))
          }
        }
      }
    }
    
    class ActivitySession: Activity {
      let audio: String
    
      init(id: String, audio: String) {
        self.audio = audio
        super.init(id: id)
      }
    
      override static func decode(json: JSON) -> Decoded<Activity> {
        return curry(ActivitySession.init)
          <^> json <| "id"
          <*> json <| "audio"
      }
    
    }
    
    class ActivityQuiz: Activity {
      override static func decode(json: JSON) -> Decoded<Activity> {
        return curry(ActivityQuiz.init)
          <^> json <| "id"
      }
    }
    
    let activities: Decoded<ThingWithActivities>? = JSONFromFile("activities").flatMap(decode)
    print(activities) 
    // => Optional(Success(ThingWithActivities(activities: [ActivitySession, ActivitySession, ActivityQuiz])))
    

    The key part is pulling out the type and .flatMaping over it to conditionally decode into the type it should be.