SwiftUI_visionOS_Note

Custom model

Mar 18, 2024
Custom model

Custom data types are frequently needed in our applications. They allow us to incorporate multiple data points into a single model. For instance, a User's data may need to encompass more than just their name. By creating a custom data type, we can encompass their name, username, email, bio, and more, all within a single object.

 

Create a navigation stack with list

 
 

Creating a custom model

IIn practice, when we have a list of users in the app, we should include more information than just the name, such as user id and username. An array of strings doesn't allow us to add this additional information. Therefore, we'll create a custom model to include more data.

 

We just created a custom model named UserModel with three data point.

and we embed the custom model into the users variables

 

Now, we change the ForEach loop with this completion.

 

and we will copy the HStack from the previous ForEach and copy to current ForEach and now it will say,

Callout icon'
Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'UserModel' conform to 'Identifiable’

Because, we added the \.self to create a fake id for users. but now new loop expect us to have the each id

 

now each UserModel will have the custom id, whenever it’s called. You can check it by writing

 
 
 
 

You might also like

BlogPro logo
Made with BlogPro