|
| 1 | +import ModelRocket |
| 2 | + |
| 3 | +/*: |
| 4 | +The **Vehicle** object has four properties, one of |
| 5 | +which is required (when using the `strictJSON` initializer). |
| 6 | + |
| 7 | +The underlying value on `Property` is always Optional. However, if the property |
| 8 | +is required and the `strictJSON` initializer is used, `value` can be force |
| 9 | +unwrapped safely, since the object will be created iff all properties where |
| 10 | +`required == true` are found in the JSON object |
| 11 | + |
| 12 | +*/ |
| 13 | + |
| 14 | +class Vehicle: ModelRocket { |
| 15 | + let model = Property<String>(key: "model") |
| 16 | + let year = Property<Int>(key: "year") |
| 17 | + let color = Property<UIColor>(key: "color") |
| 18 | + let availableColors = PropertyArray<UIColor>(key: "available_colors") |
| 19 | + let availableTrims = PropertyDictionary<Int>(key: "available_trims") |
| 20 | +/*: |
| 21 | +If you would like to avoid the use of `.value` to retrieve |
| 22 | +the underlying value of a `Property`, a good pattern to use |
| 23 | +is defining the `Property<T>` property as `private` (prefixed with a _) |
| 24 | +and declaring a separate, `public` property of type `T` |
| 25 | +*/ |
| 26 | + private let _make = Property<String>(key: "make", required: true) |
| 27 | + var make: String { |
| 28 | + set { _make.value = newValue } |
| 29 | + get { return _make.value ?? "" } |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +let json = JSON(data: dataFromResource()) |
| 34 | +if let vehicle = Vehicle(strictJSON: json) { |
| 35 | + vehicle.make |
| 36 | + vehicle.model.value |
| 37 | + vehicle.year[] |
| 38 | + |
| 39 | + for color in vehicle.availableColors { |
| 40 | + println("Color: \(color)") |
| 41 | + } |
| 42 | + |
| 43 | + for (key, value) in vehicle.availableTrims { |
| 44 | + println("Trim \(key) : \(value)") |
| 45 | + } |
| 46 | +} |
0 commit comments