Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.7k views
in Technique[技术] by (71.8m points)

ios - 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...