An explanation of how SwiftUI works coming from a React background

Arnaud
Arnaud
Jul 25 · 2 min read

Basic Components

  • function/class turns into struct
  • React.Component becomes View, a pure UI element
  • function return/render(...) becomes var body: some View { ... }

State

Initialization

Use the @State decorator to define a state property for your component:

Pretty straight-forward. Use self.stateProperty instead of this.state, just as any struct property.

Update

No setState, no setProperty, just update the value right away and the component will re-render accordingly.


Props

Props should be defined using component properties:

  • Set default values:
var message: String = "Goodbye"
  • Props here are just as immutable as in React
  • Props can become mutable by setting:
// Calling component
@State var message = "Hello"
Home(message: $message)
// Home
@Binding var message: String
  • the property here is a state property because we need to keep a reference on it as it will be mutated
  • notice the $ in front of the message variable, indicating that this value is a binding (two-way binding)
  • @Binding indicates this relationship between the child and its parent

Lifecycle

Pretty limited, as we only get hooks for didMount and willUnmount using onAppear and onDisappear respectively:


Fragments

Similar to React.Fragment, Group comes handy:


Style

Basics

Use view modifiers to define styles:

Layout

Forget about div:

  • Use HStack for horizontal layout
  • Use VStack for vertical layout
  • Use ZStack for stacking views on top of each other

Optional Rendering

Instead of value && (...), use if value != nil { ... }:


Gestures

onClick becomes tapAction:

Many more gestures are available, yet less intuitive to implement at first.

Majid Jabrayilov wrote a really great article about gestures in SwiftUI, that I encourage you to read if you are curious.


Where to Go From Here?


If you are curious to know more, you can follow me on Medium (or Github).

Any thoughts about the syntax, SwiftUI potential? 🙋

Better Programming

Advice for programmers.

Arnaud

Written by

Arnaud

23. I often find myself reading too many articles on the internet.

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