Skip to content

Commit 0a0ee5d

Browse files
committed
update readme
1 parent 8ddf332 commit 0a0ee5d

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

README.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,63 @@ func main() {
118118
}
119119
```
120120

121+
### Type Safety with Models
122+
123+
The Appwrite Swift SDK provides type safety when working with database documents through generic methods. Methods like `listDocuments`, `getDocument`, and others accept a `nestedType` parameter that allows you to specify your custom model type for full type safety.
124+
125+
```swift
126+
struct Book: Codable {
127+
let name: String
128+
let author: String
129+
let releaseYear: String?
130+
let category: String?
131+
let genre: [String]?
132+
let isCheckedOut: Bool
133+
}
134+
135+
let databases = Databases(client)
136+
137+
do {
138+
let documents = try await databases.listDocuments(
139+
databaseId: "your-database-id",
140+
collectionId: "your-collection-id",
141+
nestedType: Book.self // Pass in your custom model type
142+
)
143+
144+
for book in documents.documents {
145+
print("Book: \(book.name) by \(book.author)") // Now you have full type safety
146+
}
147+
} catch {
148+
print(error.localizedDescription)
149+
}
150+
```
151+
152+
**Tip**: You can use the `appwrite types` command to automatically generate model definitions based on your Appwrite database schema. Learn more about [type generation](https://appwrite.io/docs/products/databases/type-generation).
153+
154+
### Working with Model Methods
155+
156+
All Appwrite models come with built-in methods for data conversion and manipulation:
157+
158+
**`toMap()`** - Converts a model instance to a dictionary format, useful for debugging or manual data manipulation:
159+
```swift
160+
let user = try await account.get()
161+
let userMap = user.toMap()
162+
print(userMap) // Prints all user properties as a dictionary
163+
```
164+
165+
**`from(map:)`** - Creates a model instance from a dictionary, useful when working with raw data:
166+
```swift
167+
let userData: [String: Any] = ["$id": "123", "name": "John", "email": "john@example.com"]
168+
let user = User.from(map: userData)
169+
```
170+
171+
**`encode(to:)`** - Encodes the model to JSON format (part of Swift's Codable protocol), useful for serialization:
172+
```swift
173+
let user = try await account.get()
174+
let jsonData = try JSONEncoder().encode(user)
175+
let jsonString = String(data: jsonData, encoding: .utf8)
176+
```
177+
121178
### Error Handling
122179

123180
When an error occurs, the Appwrite Swift SDK throws an `AppwriteError` object with `message` and `code` properties. You can handle any errors in a catch block and present the `message` or `localizedDescription` to the user or handle it yourself based on the provided error information. Below is an example.

0 commit comments

Comments
 (0)