Skip to content

Commit

Permalink
Merge pull request JohnSundell#90 from plain-vanilla-games/update-rea…
Browse files Browse the repository at this point in the history
…dme-to-use-extensions

Update README to declare Unboxable in extension of struct
  • Loading branch information
JohnSundell authored Jul 18, 2016
2 parents be16a30 + 559932b commit b92074c
Showing 1 changed file with 15 additions and 7 deletions.
22 changes: 15 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,12 @@ That can be initialized with the following JSON:
To decode this JSON into a `User` instance, all you have to do is make `User` conform to `Unboxable` and unbox its properties:

```swift
struct User: Unboxable {
struct User {
let name: String
let age: Int
}

extension User: Unboxable {
init(unboxer: Unboxer) {
self.name = unboxer.unbox("name")
self.age = unboxer.unbox("age")
Expand All @@ -57,15 +59,17 @@ let user: User = try Unbox(data)
The first was a pretty simple example, but Unbox can decode even the most complicated JSON structures for you, with both required and optional values, all without any extra code on your part:

```swift
struct SpaceShip: Unboxable {
struct SpaceShip {
let type: SpaceShipType
let weight: Double
let engine: Engine
let passengers: [Astronaut]
let launchLiveStreamURL: NSURL?
let lastPilot: Astronaut?
let lastLaunchDate: NSDate?
}

extension SpaceShip: Unboxable {
init(unboxer: Unboxer) {
self.type = unboxer.unbox("type")
self.weight = unboxer.unbox("weight")
Expand All @@ -80,34 +84,38 @@ struct SpaceShip: Unboxable {
}
}

enum SpaceShipType: Int, UnboxableEnum {
enum SpaceShipType: Int {
case Apollo
case Sputnik
}

extension SpaceShipType: UnboxableEnum {
static func unboxFallbackValue() -> SpaceShipType {
return .Apollo
}
}

struct Engine: Unboxable {
struct Engine {
let manufacturer: String
let fuelConsumption: Float
}

extension Engine: Unboxable {
init(unboxer: Unboxer) {
self.manufacturer = unboxer.unbox("manufacturer")
self.fuelConsumption = unboxer.unbox("fuelConsumption")
}
}

struct Astronaut: Unboxable {
struct Astronaut {
let name: String
}

extension Astronaut: Unboxable {
init(unboxer: Unboxer) {
self.name = unboxer.unbox("name")
}
}


```

### Error handling
Expand Down

0 comments on commit b92074c

Please sign in to comment.