In SwiftUI is there any problem to put subview in function in places of structs?

Viewed 47

In some cases, the struct design in heavier than func design, for little subviews. But is there any problem to use functions rather than structs?

Eg:

func ƒText(_ text: String, fontSize: CGFloat = 13) -> some View {
    Text(text)
        .font(.system(size: fontSize))
}

compared to:

struct sText: View {
    let text: String
    let fontSize: CGFloat
    init(_ text: String, fontSize: CGFloat = 13) {
        self.text = text ; self.fontSize = fontSize
    }
    var body: some View {
        Text(text)
            .font(.system(size: fontSize))
    }
}
2 Answers

Use a function or computed property if you don't need to introduce DynamicProperties. E.g. if you need a new @State variable, there's no way to use it without a new View type.

We can do this, BUT there is a big difference - in case of a) function the content will be recreated (read re-rendered) at every caller refresh independently of arguments, in case of b) view an init will be called, however its body is NOT if arguments are the same. Ie. SwiftUI engine is optimised to track changes in sub-views and does not re-render sub-views (using cache). However function is always called and executed completely.

Demo:

var body: some View {
  ƒText("Hello")    // new Text("Hello") created every call
}

var body: some View {
  sText("Hello")    // Text("Hello") created once !!
}
Related