Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct 'State' cannot be used as an attribute

I have the following code in a ContentView.swift file:

struct ContentView: View {
    @State private var selectedSpeed: Int = 1
    
    var body: some View {
        Text("Hello World")
    }
}

I have simplified it for the sake of readability. I know that selectedSpeed is not being used.

In the line where selectedSpeed is declared, I'm getting the following error: Struct 'State' cannot be used as an attribute

Interestingly, pasting the exact same code in a Playground builds successfully. I'm on Xcode 12.1. I've tried the combo of nuking derived data and re-opening Xcode but the error persists. Any ideas what is wrong here?

like image 237
jjramos Avatar asked Nov 19 '25 07:11

jjramos


2 Answers

It turned out that I had a struct called State in my project and that caused the problem.

TL;DR: Never call any of your structs, and potentially classes, State if you're planning on using SwiftUI. I would expand it to not name any of your classes or structs with something that clashes with a property wrapper.

That also explains why everything was ok in the Playground.

The Report navigator was actually giving me the hint

enter image description here

like image 179
jjramos Avatar answered Nov 20 '25 20:11

jjramos


The name State is not protected and as per your reply/answer you have State declared elsewhere, either in your own app or inside a dependency that you might be importing into that file.

You can tell the compiler what symbol to use by explicitly setting the correct "Namespace".

For example:

struct ContentView: View {
    @SwiftUI.State private var selectedSpeed: Int = 1
    
    var body: some View {
        Text("Hello World")
    }
}
like image 33
vfn Avatar answered Nov 20 '25 20:11

vfn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!