13

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?

jjramos
  • 1,874
  • 14
  • 22

2 Answers2

31

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

jjramos
  • 1,874
  • 14
  • 22
  • Dang, TY. Same exact thing for me. Just changed my objects to: StateObj, CityObj and CountryObj just to be safe. – DaWiseguy Oct 18 '21 at 22:42
  • Thanks for sharing the reason behind this issue. You've just saved me hours of scratching my head. – Solomiya Jan 24 '22 at 09:42
  • Thanks for your comment. That is the main reason why I decided to share in the first place! I had already lost a couple of hours understanding what was wrong :D – jjramos Jan 25 '22 at 10:34
12

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")
    }
}
Bill Chan
  • 3,199
  • 36
  • 32
vfn
  • 6,026
  • 2
  • 34
  • 45
  • 1
    Turns out that the app that I currently maintained for the company that I work for uses State keyword long before SwiftUI is around. Your answer really helped me so that i dont have to do major refactor since it is used on a lot of places. – Gamz Rs Mar 30 '23 at 04:38