This article has been archived, as it was published several years ago, so some of its information might now be outdated. For more recent articles, please visit the main article feed.
Refactoring SwiftUI views using functions
Discover page available: SwiftUII 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()
}
}
}

Swift by Sundell is brought to you by the Genius Scan SDK — Add a powerful document scanner to any mobile app, and turn scans into high-quality PDFs with one line of code. Try it today.