Skip to content

Commit

Permalink
update README.md
Browse files Browse the repository at this point in the history
  • Loading branch information
uatuko committed Jun 13, 2022
1 parent 3d60b5e commit 32f61db
Showing 1 changed file with 43 additions and 1 deletion.
44 changes: 43 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ sortable property of the id.
## Usage

```swift
let id = NewXid()
let id: String = NewXid() // or let id: Id = NewXid()
print(id)
// Output: caia5ng890f0tr46f690
```
Expand All @@ -83,6 +83,48 @@ print(id.data as NSData)
// Output: {length = 12, bytes = 0x62a4a4a108481e0f9b83781f}
```

### Encoding and Decoding

The `Id` structure complies with `Codable` protocol and can be converted into and out of an external representation (e.g. JSON).

#### Decoding from JSON

```swift
struct User: Decodable {
var id: Id
var name: String
}

let data = """
{
"id": "caia5ng890f0tr00hgtg",
"name": "Jane Smith"
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let user = try decoder.decode(User.self, from: data)

print(user.id)
// Output: caia5ng890f0tr00hgtg
```

#### Encoding into JSON
```swift
struct User: Encodable {
var id: Id
var name: String
}

let user = User(id: NewXid(), name: "Jane Smith")

let encoder = JSONEncoder()
let data = try encoder.encode(user)

print(String(data: data, encoding: .utf8)!)
// Output: {"id":"caia5ng890f0tr00hgtg","name":"Jane Smith"}
```


[^1]: https://www.mongodb.com/docs/manual/reference/method/ObjectId/
[^2]: https://datatracker.ietf.org/doc/html/rfc4648#section-7
Expand Down

0 comments on commit 32f61db

Please sign in to comment.