Pregunta

I am working on JSON model classes in a swift project. Examples of the sample JSON and classes are below. In the JSON response, there can be many different unique statistics returned, but they all follow the same JSON dictionary pattern. The challenge that I ran into was the the value in the JSON result can be an integer, a float and sometimes an integer that's really an enum. Is it better design to have an empty subclass or typealias the base class so I can refer to it with a meaningful name. There will be no functionality added to the child classes. At this point I only see myself using them for naming.

Code samples are below.

JSON
"score": { /* <- statistic identified */
  "basic": {
    "value": 2410 /* <- value can be an int, float or int thats really an enum */
    "displayValue": "2410" /* <- string value for human consumption */
  }
}

Swift model class
Double and Enum classes snipped out for brevity

public class IntValueBase : ValueBase {
  public private(set) var value: Int = 0
  public required init(json: JSON) throws {
    try super.init(json: json)
    self.value = try json.int("basic", "value")
  }
}

// Typealias option
typealias Score = IntValueBase

// inheritance option
public class Score: IntValueBase {}
¿Fue útil?

Solución

This is pretty much the point of the typealias functionality in swift, per the documentation, so I think that's the way you should go.

Otros consejos

I used an enum to implement this sort of thing. It works a lot like a type safe C union:

enum AttributeValueType {
    case Text(String)
    case DateTime(NSDate)
    case Flag(Bool)
    case Count(Int)
    case Decimal(Double)
}

extension AttributeValueType {
    // I'm using SwiftyJSON, hence the `JSON` type
    init(json: JSON) {
        switch json["type"].string! {
        case "text":
            self = .Text(json["data"].string!)
        case "date_time":
            let dateString = json["data"].string!
            let date = dateTimeFormatter.dateFromString(dateString)!
            self = .DateTime(date)
        case "flag":
            self = .Flag(json["data"].bool!)
        case "count":
            self = .Count(json["data"].int!)
        case "decimal":
            self = .Decimal(json["data"].double!)
        default:
            fatalError("missing type = \(json.string!)")
        }
    }
}

In my use-case, I get JSON like the following:

{
    "type": "text",
    "data": "Hello World"
},
{
    "type": "flag",
    "data": true
},
{
    "type": "count",
    "data": 34
}
Licenciado bajo: CC-BY-SA con atribución
scroll top