SwiftUI: Reusable Components/Higher-Order-Components

How to use and manipulate HOC’s

Andrei Villasana
Jun 29 · 2 min read
Photo by Tyler Lastovich on Unsplash

**It seems Safari isn’t able to show code snippets, please try using Chrome**

If you’ve ever worked with React or React-Native, Higher-Order-Components are the design pattern of choice when reusing component behavior and UI.

This pattern isn’t foreign to iOS either. Check out this article on creating custom components on iOS.

SwiftUI’s HOC Syntax — The Right Way

Let's keep it really simple now. This is all the code that we need in order to create a Higher-Order-Component in SwiftUI:

Note: In the initializer, I purposely set _ childView to conform to a closure type that returns our generic View, this makes the code more readable. Alternatively, you can set it as this…_ childView: C and call ContainerView(Text("Hello!"))

  1. ContainerView declares a generic constraint for our View, a.k.a Type Constraint Syntax
  2. We store the generic type as a property named childView
  3. Within body we return the childview
  4. Simple! HOC successfully created!

Practical Example

Let’s get serious, we can’t truly appreciate HOC without a good practical example, let's dig in!

What if we try to create a component that would give every child the ability to become draggable and spring back to their original position when released.

First, we need to create a new View component that we will name DraggableView that adopts the HOC Syntax we wrote earlier.

Second, we have to write the business logic for the drag gesture and spring animation.

We can put DraggableView into action by passing in the child components for rendering!

Final Thoughts!

Voila! Just like that, we are done! I wasn't able to find any articles on creating HOC’s for SwiftUI, but I hope you enjoyed reading this article as much as I enjoyed writing it!

I’d also recommend checking this article on creating your own custom view modifiers, just like their name they modify your View.

Let me know your thoughts!

Better Programming

Advice for programmers.

Andrei Villasana

Written by

Software Enthusiast

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade