2

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))
    }
}
1
  • 2
    As long as it is implemented in a @ViewBuilder there is no problem. You can use computed variables as well. Commented May 19, 2022 at 21:03

2 Answers 2

1

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 !!
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.