0Pricing
SwiftUI Academy · Aula

Declarando propriedades @State

Adicione @State para armazenar dados mutáveis locais à visualização.

Declarando propriedades @State é uma aula grátis de SwiftUI Academy no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de SwiftUI Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de SwiftUI Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Meet the @State Wrapper

You declare mutable view-local data by marking a property with @State. This property wrapper tells SwiftUI to store and watch the value for you. 🏷️

@State private var count = 0

Always Give It a Default

A @State property needs an initial value right where you declare it. SwiftUI uses it to create the storage the first time the view appears.

@State private var isOn = false

Mark It private

State belongs to one view, so declare it private. This signals that no outside code should reach in and set it directly, keeping ownership clear.

@State private var name = ""

Reading the Value

Read a @State property like any normal variable. Just use its name in body and SwiftUI tracks that this view depends on it.

Text("You tapped \(count) times")

Writing the Value

You can mutate a @State property even though the view is a struct. Assign to it from an action and SwiftUI schedules a redraw automatically.

Button("Add") { count += 1 }

It Persists Across Redraws

SwiftUI keeps the @State value alive across the many times the view body is recomputed. Your count won't reset just because the view redrew.

Putting It Together

Declare state, read it in the body, and mutate it from a button. That is the full loop that powers most simple interactions.

struct CounterView: View {
    @State private var count = 0
    var body: some View {
        Button("Count \(count)") { count += 1 }
    }
}

Use Simple Value Types

@State works best with value types like Int, Bool, String, or small structs. For shared objects you'll later reach for other tools, but values are the norm here.

One Owner Per Property

The view that declares @State is its owner. Other views can receive access, but only one view should hold the original state for a given value.

Don't Overuse It

Reach for @State only when a value truly changes while the view is on screen. Constant labels and passed-in data don't need it.

Naming for Clarity

Name state for what it represents, like isLoading or selectedTab. Clear names make the data flow obvious to anyone reading the view.

Quick Check

Which line correctly declares a private piece of view-local state?

Recap

Declare changing view data with @State, give it a default, and keep it private. Read it freely in body and mutate it from actions to trigger redraws. ✅

Perguntas Frequentes

A aula “Declarando propriedades @State” é grátis?

Sim — o texto completo de “Declarando propriedades @State” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de SwiftUI Academy, atualize para CoddyKit PRO. O curso de SwiftUI Academy inclui 4 aulas no total.

O que vou aprender em “Declarando propriedades @State”?

Adicione @State para armazenar dados mutáveis locais à visualização. Você pratica SwiftUI Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar SwiftUI Academy?

Nenhuma experiência prévia é necessária. SwiftUI Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.

Quanto tempo leva a aula “Declarando propriedades @State”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de SwiftUI Academy?

Sim. Cada aula de SwiftUI Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Por que as visualizações precisam de estado
  2. Declarando propriedades @State
  3. Criando um contador de toques
  4. Alternando a visibilidade com estado
← Voltar para SwiftUI Academy