3

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 {}
asked Feb 24, 2016 at 21:34

2 Answers 2

5

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.

answered Feb 24, 2016 at 22:22
0

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
}
answered Mar 17, 2016 at 21:19

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.