For a given screen, should each view be separated into different files, or all kept in the same file

Viewed 77

My code:

struct HomeMapView: View {

    var body: some View {
            VStack {
                HomeHeader()
                Spacer()
                HomeFooter()
        }
}

struct HomeHeader: View {

    var body: some View {
            Text("Header")
        }
}

struct HomeFooter: View {

    var body: some View {
             Text("Footer")
        }
}

I am new to swift, so excuse the simplicity. Trying to get a grasp on project structure and theory. My question: Would it be better to separate the HomeHeader and HomeFooter view into separate respective files, or keep the them in the file of the view that uses them?

If any additional clarification is needed, leave a comment.

2 Answers

It is better separated(using Views in View), because it make less render to HomeMapView(), if HomeMapView() should get rendered it will go render it all body, but if you separated, it will understand it and it will not render it if there is no update for that!

Ps: it does not matter if you create a new file or keep them all in one file, you can separated them to deferent files as you like it make it easy for you to maintain them.

Your concept of using HomeMapView, HomeHeader, HomeFooter is important and keep that concept alive, using them in deferent file is up to you! no deference there.

Making reusable views is a fundamental concept in SwiftUI, and it accelerates development times, and increases reusability significantly!

Putting HomeHeader, and HomeFooter in seperate files makes no deference in terms of its functionality. However it may be used to improve the file structure (beneficial for team-based environments).

Personally, if HomeHeader, and HomeFooter is a reusable component that I will be using in other views other then HomeMapView, then, I will put them in seperate files HomeHeader.swift, and HomeFooter.swift

However, if these views are only related to this view, then I will keep them in the same file.

Finally, this is subjective and depends on what the devleloper(s) finds suitable.

Best of luck!

Related