Articles, podcasts and news about Swift development, by John Sundell.

Refactoring SwiftUI views using functions

Published on 06 Jun 2019
Discover page available: SwiftUI

I see lots of SwiftUI comments about how it’ll “force” developers to write “Pyramids of Doom” with heavily nested code, which is just as false as MVC forcing developers to build massive view controllers. Here’s one example of how nesting can be avoided, by using inline functions:

struct MyView: View {
    var body: some View {
        func makeVStack() -> some View {
            VStack {
                ForEach(0..<5) { _ in makeHStack() }
            }
        }

        func makeHStack() -> some View {
            HStack {
                Text("Leading")
                Text("Trailing")
            }
        }

        return ZStack {
            Color.gray
            makeVStack()
        }
    }
}

Support Swift by Sundell by checking out this sponsor:

Essential Developer

Essential Developer: Learn the most up-to-date techniques and strategies for testing new and legacy Swift code in this free practical course for developers who want to become complete senior iOS developers. This virtual event includes lectures, mentoring sessions, and step-by-step instructions. Click to learn more.