Skip to content

Commit d9de933

Browse files
committed
update readme
1 parent 78f3cb3 commit d9de933

1 file changed

Lines changed: 57 additions & 0 deletions

File tree

README.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,63 @@ func main() {
163163
}
164164
```
165165

166+
### Type Safety with Models
167+
168+
The Appwrite Apple 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.
169+
170+
```swift
171+
struct Book: Codable {
172+
let name: String
173+
let author: String
174+
let releaseYear: String?
175+
let category: String?
176+
let genre: [String]?
177+
let isCheckedOut: Bool
178+
}
179+
180+
let databases = Databases(client)
181+
182+
do {
183+
let documents = try await databases.listDocuments(
184+
databaseId: "your-database-id",
185+
collectionId: "your-collection-id",
186+
nestedType: Book.self // Pass in your custom model type
187+
)
188+
189+
for book in documents.documents {
190+
print("Book: \(book.name) by \(book.author)") // Now you have full type safety
191+
}
192+
} catch {
193+
print(error.localizedDescription)
194+
}
195+
```
196+
197+
**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).
198+
199+
### Working with Model Methods
200+
201+
All Appwrite models come with built-in methods for data conversion and manipulation:
202+
203+
**`toMap()`** - Converts a model instance to a dictionary format, useful for debugging or manual data manipulation:
204+
```swift
205+
let user = try await account.get()
206+
let userMap = user.toMap()
207+
print(userMap) // Prints all user properties as a dictionary
208+
```
209+
210+
**`from(map:)`** - Creates a model instance from a dictionary, useful when working with raw data:
211+
```swift
212+
let userData: [String: Any] = ["$id": "123", "name": "John", "email": "john@example.com"]
213+
let user = User.from(map: userData)
214+
```
215+
216+
**`encode(to:)`** - Encodes the model to JSON format (part of Swift's Codable protocol), useful for serialization:
217+
```swift
218+
let user = try await account.get()
219+
let jsonData = try JSONEncoder().encode(user)
220+
let jsonString = String(data: jsonData, encoding: .utf8)
221+
```
222+
166223
### Error Handling
167224

168225
When an error occurs, the Appwrite Apple 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)