Skip to content
This repository has been archived by the owner on Jun 18, 2019. It is now read-only.

Commit

Permalink
README: Add example on how to use UnboxFormatter
Browse files Browse the repository at this point in the history
  • Loading branch information
JohnSundell committed Feb 1, 2017
1 parent 2a78376 commit 352982b
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,59 @@ struct UniqueIdentifier: UnboxableByTransform {
}
```

### Formatters

If you have values that need to be formatted before use, Unbox supports using formatters to automatically format an unboxed value. Any `DateFormatter` can out of the box be used to format dates, but you can also add formatters for your own custom types, like this:

```swift
enum Currency {
case usd(Int)
case sek(Int)
case pln(Int)
}

struct CurrencyFormatter: UnboxFormatter {
func format(unboxedValue: String) -> Currency? {
let components = unboxedValue.components(separatedBy: ":")

guard components.count == 2 else {
return nil
}

let identifier = components[0]

guard let value = Int(components[1]) else {
return nil
}

switch identifier {
case "usd":
return .usd(value)
case "sek":
return .sek(value)
case "pln":
return .pln(value)
default:
return nil
}
}
}
```

You can now easily unbox any `Currency` using a given `CurrencyFormatter`:

```swift
struct Product: Unboxable {
let name: String
let price: Currency

init(unboxer: Unboxer) throws {
name = try unboxer.unbox(key: "name")
price = try unboxer.unbox(key: "price", formatter: CurrencyFormatter())
}
}
```

### Supports JSON with both Array and Dictionary root objects

No matter if the root object of the JSON that you want to unbox is an `Array` or `Dictionary` - you can use the same `Unbox()` function and Unbox will return either a single model or an array of models (based on type inference).
Expand Down

0 comments on commit 352982b

Please sign in to comment.