Why `var body: some View` is a property(vs method) in SwiftUI?

Hi folks,
I just want to clarify for myself some things, in SwiftUI in protocol View we have a required property var body: some View { get }. In most of the cases samples, the is a computed property. As I know a good practice for computed properties to have time complexity O(1) but in SwiftUI we can have ForEach and other code that can be larger than O(1). Also in Swift API Design Guidelines Begin names of factory methods with “make”, e.g. x.makeIterator().

Any thoughts on why body is declared as property but not as a method func body() -> some View?

1 Like

In my experience, many people still believe this. But to me, it's just dogma, primarily coming from people who didn't have any choice but writing methods, for most of their career. Complexity works for anything. Use it as appropriate, like the guidelines recommend.

/// - Complexity: O(🪵n)
var property…

Yes, the distinction between properties and methods that return objects can be fuzzy.

I think the expectation for a property is that it returns information about the state of the object or returns some part of the object. So the computed property might have to do a simple calculation or a lookup of some kind but it's not a heavyweight effort. It might generate a new object lazily and then cache that value to be returned on subsequent queries.

There's plenty of discussion of this topic online.

Note that Apple and Swift naming conventions for properties are to use nouns, like body, and no makeBody or getBody is used.

1 Like

Usually, my criteria for func vs var is that: var doesn't change unless self changes.


in SwiftUI we can have ForEach and other code that can be larger than O(1).

For what it's worth, ForEach is just an instruction to SwiftUI to iterate over the provided collection and invoke the provided closure at some point later when SwiftUI decides to render. No O(n) operation is occurring inside body as a result of ForEach.


Thanks everyone, for me this more clear now.

1 Like
Terms of Service

Privacy Policy

Cookie Policy