Why does SwiftUI define views using Struct?

ByungwookAn
3 min readOct 21, 2023

--

Intro

When you program using UIKit, you’ll know they use Class for views.

But in SwiftUI, When you make a new project, you can see SwiftUI defines views using Struct.

Today, I’ll talk about why SwiftUI defines views as Struct instead of Class and the advantages of Struct.

The reason for SwiftUI defines Views using Struct

  1. Minimize variability

As you know, Class is based on reference type, and Struct is based on value type. So you don’t have to worry about an unexpected side effect when you use Struct instead of Class. So Struct is more advantageous in tracking changes in data than Class.

SwiftUI encourages us to move to a more functional design approach. Using Struct instead of Class in the View is the basic element of functional programming.

2. Performance

Struct is faster and simpler than Class. Class-based views create views based on inheritance. So it inherits many properties and methods. It makes Class-based views heavy and complicated.

But Struct-based view, the Struct does not inherit from the parent class. The Struct-based view contains only what you made.

Also, if you use Struct instead of Class, You can improve performance by easily detecting changes in the structure.

3. Protect from a Memory leak

If you use the reference type class, there is a possibility of memory leak. Memory leaks happen when dynamically allocated memory is not properly deallocated. But value type structure enables secure programming in a memory leak.

Why does UIKit create Class-based views?

UIKit still adopts a Class-based view instead of a Struct-based view like SwiftUI. If you’ve read my post, you might wonder why UIKit still uses Class-based views. So here’s the reason why UIKit still uses a Class-based view.

  1. Compatibility with Objective-C

In Objective-C, objects are typically represented as instances of classes. Also, many existing APIs and libraries are Class-based. So UIKit still adopts Class-based views to compatibility with Objective-C.

2. Maximize the benefits of inheritance

UIKit allows for dynamic behaviors and extensibility through features like subclassing, method swizzling, and dynamic dispatch because it is based on Class. It can be useful for customizing and extending UIKit components.

Conclusion

SwiftUI is a more modern and declarative approach to building user interfaces. If you adopt a struct-based view, It may meet SwiftUI’s ultimate goal, and you can make your views more simple, safe, and concise. The difference between Class and Structure shows the difference between UIKit and SwiftUI’s ultimate goal.

Reference

--

--