SwiftUI_visionOS_Note

Custom model

Mar 18, 2024
2 min read|

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

struct ContentView: View {
    
    @State var users: [String] = [
        "Nick", "Emma", "Samuel", "Chirs"
    ]
    
    var body: some View {
        NavigationStack {
            List {
                ForEach(users, id: \.self) { name in
                    HStack(spacing: 16) {
                        Circle()
                            .frame(width: 30, height: 30)
                            .foregroundStyle(.blue)
                        Text(name)
                    }
                    .padding(.vertical, 8)
                }
            }
            .navigationTitle("Custom Model")
        }//END: NAV
    }
}
swift

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.

struct UserModel{
    let displayName: String
    let userName: String
    let followerCount: Int
}
swift

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

and we embed the custom model into the users variables

    @State var users: [UserModel] = [
        UserModel(displayName: "Nick", userName: "nick123", followerCount: 100)
        UserModel(displayName: "Emma", userName: "emma123", followerCount: 123)
        UserModel(displayName: "Samuel", userName: "sam123", followerCount: 999)
        UserModel(displayName: "Christ", userName: "christ666", followerCount: 666)
    ]
swift

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,

⚠️
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

struct UserModel: Identifiable{
    let id: String = UUID().uuidString
    let displayName: String
    let userName: String
    let followerCount: Int
}
swift

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

Text(user.id)
swift

Subscribe to our newsletter

Get the latest news and updates from our team